如何从JSON字符串中检索键和值 [英] How to retrieve key and value from JSON String
本文介绍了如何从JSON字符串中检索键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下格式的JSON字符串:
I have a JSON String in this format:
{
"supplier": {
"mov_10": "love actually",
"mov_1": "fare"
},
"quantity": 20,
"success": true,
"length":2
}
现在,我想使用supplier
对象(同时使用键和值)在下面创建一个选择框,如下所示:
Now I want to create a select box below using the supplier
object (using both the keys and values), like this:
<select id="selectme">
<option id="mov_10">love actually</option>
<option id="mov_1">fare</option>
</select>
那么我该如何创建它?我只想知道如何在对象中到达mov_10
和mov_1
.
对不起,我的英语不好,但是请帮助我.
So how do I create it? I just want to know how to reach mov_10
and mov_1
in the object.
Sorry for my bad English, but please help me.
谢谢.
推荐答案
如果我正确理解了这个问题,我认为您可能需要使用以下方法:
If I understood the question correctly, I think you might want to use something along this:
var jsonArray = ... ; // {"supplier": ... } (JS Object)
var supplierOptions = jsonArray.supplier;
// TODO: remember to set up selectme!
for(var optionId in supplierOptions) {
if(!supplierOptions.hasOwnProperty(optionId)) {
continue;
}
var optionValue = supplierOptions[optionId];
// operate with name and value here (append to select ie.)
$("#selectme").append('<option id="' + optionId + '">' + optionValue + '</option>');
}
该代码可能需要进行一些清理.希望它传达了基本思想.
The code probably could use some cleaning up. Hopefully it conveys the basic idea, though.
这篇关于如何从JSON字符串中检索键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文