如何使用jQuery从JSON获取属性值

时间:2012-05-03 13:16:08

标签: jquery json

我使用Newtonsoft dll从xml文件生成json。从下面我将如何将地址详细信息放入列表中(如果示例中有更多内容)并将它们写入下拉列表中我有以下有效的json(已检查onjsonlint):

{
    "?xml": {
        "@version": "1.0",
        "@encoding": "utf-8"
    },
    "Root": {
        "Information": {
            "Error": {
                "ErrorNo": "0",
                "ErrorMsg": null
            },
            "Address": {
                "Address": [
                    {
                        "@AddressID": "14961943",
                        "@Sequence": "1",
                        "@Description": "Some Company Name, Some Building, 10 Some Street, Some County, Some City"
                    }            
                ]
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

试试这个:

var json = // that object above
var addresses = json.Root.Information.Address.Address;

for (var i = 0; i < addresses.length; i++) {
    var $option = $("<option></option>").val(addresses[i]["@AddressID"]).text(addresses[i]["@Description"]);
    $("#mySelect").append($option);
}

Example fiddle

答案 1 :(得分:0)

不使用jQuery的解决方案:

var select = document.getElementById('selectID');
var addresses = json.Root.Information.Address.Address;

for(var i = 0, l = addresses.length; i < l; i++) {
  var o = document.createElement('option');
  o.value = addresses[i]['@AddressID'];
  o.innerHTML = addresses[i]['@Description'];
  select.appendChild(o);
}