开发者

How to retrieve key and value from JSON String

开发者 https://www.devze.com 2023-01-01 03:30 出处:网络
I have a JSON String in this format: { \"supplier\": { \"mov_10\": \"love actually\", \"mov_1\": \"fare\"

I have a JSON String in this format:

{
  "supplier": {
    "mov_10": "love actually",
    "mov_1": "fare"
  },
  "quantity": 20,
  "success": true,
  "length":2
}

Now I want to create a select box below using the supplier object (using both the keys and values), like this:

<sele开发者_开发问答ct id="selectme">
    <option id="mov_10">love actually</option>
    <option  id="mov_1">fare</option>
</select>

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.

Thanks.


Use the for...in statement to iterate over keys:

for ( var k in someObject.supplier ) {
    someOption.value = k;
    someOption.text  = someObject.supplier[ k ];
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消