无法访问 JSON 中的字段

Cannot access a field in JSON

本文关键字:字段 JSON 访问      更新时间:2023-09-26

我正在尝试访问 JSON 响应中的图像,但是我需要访问的字段是唯一的 id 值,或者更确切地说是随机的。我们正在从服务器获取这些数据,因此我们无法对 id 进行硬编码。

JSON如下:

 { "error" : { "occured" : "false" },
"errors" : [  ],
"executiontime" : 2500,
"metadata" : {  },
"value" : [ { "activity_duration" : "1 hour, ½ day & full day packages",
    "adult_rate_high_period_high_price" : 275,
    "adult_rate_high_period_low_price" : 49,
    "adult_rate_low_period_high_price" : "",
    "adult_rate_low_period_low_price" : "",
    "amenities" : [  ],
    "assets" : { "logo" : { "436209" : { "asset_type" : "image",
                "caption" : "",
                "credit" : "",
                "description" : "",
                "exists" : "true",
                "height" : 82,
                "label" : "Copy of Monarch logo",
                "latitude" : 0,
                "longitude" : 0,
                "market" : "$",
                "o_id" : 3221685,
                "type_o_id" : 2543991,
                "unique_id" : 436209,
                "url" : "http://c0481729.cdn2.cloudfiles.rackspacecloud.com/p-DD951E3E-C7AF-F22C-77E98D299833B38F-2544001.jpg",
                "width" : 220
              } },

我们正在尝试显示每种便利设施的业务徽标。为此,我需要访问上述 JSON 中的 url 字段。如何访问 assest 下的 url 字段。

问题是获取徽标436209的 id。

var theid;
var l = obj.value[0].assets.logo
for (var p in l) {
  if (l[p].hasOwnProperty('unique_id')) {
     theid = l[p].unique_id;
     break;
  }
}

这是未经测试的。这个想法是使用 in -运算符来迭代徽标对象的属性并获取具有unique_id的属性。

更正:

obj.value[0].assets.logo["436209"].url = 'foo';
// or
var foo = obj.value[0].assets.logo["436209"].url;

这假设您的对象格式正确,并且继续使用 obj.value[0] 的更多部分。

具体来说,如果你的对象已经完成,也许是这样的:

var obj = {
    "error": { "occured": "false" },
    "errors": [],
    "executiontime": 2500,
    "metadata": {},
    "value": [{
        "activity_duration": "1 hour, ½ day & full day packages",
        "adult_rate_high_period_high_price": 275,
        "adult_rate_high_period_low_price": 49,
        "adult_rate_low_period_high_price": "",
        "adult_rate_low_period_low_price": "",
        "amenities": [],
        "assets": {
            "logo": {
                "436209": {
                    "asset_type": "image",
                    "caption": "",
                    "credit": "",
                    "description": "",
                    "exists": "true",
                    "height": 82,
                    "label": "Copy of Monarch logo",
                    "latitude": 0,
                    "longitude": 0,
                    "market": "$",
                    "o_id": 3221685,
                    "type_o_id": 2543991,
                    "unique_id": 436209,
                    "url": "http://c0481729.cdn2.cloudfiles.rackspacecloud.com/p-DD951E3E-C7AF-F22C-77E98D299833B38F-2544001.jpg",
                    "width": 220
                }
            }
        }
    }]
};