【问题标题】:Is it possible to assign a key within another key in JSON?是否可以在 JSON 中的另一个键中分配一个键?
【发布时间】:2014-03-08 23:17:13
【问题描述】:

是否可以在 JSON 中的键中包含一个键,(如果有)我将如何在 jQuery 中访问它? 这是我的代码:

{
    "product": [{
        "category": "Clothing",
        "items": [{
            "name": "Shirt",
            "price": "$4.99"
        }]
    }, {
        "category": "Food",
        "items": []
    }, {
        "category": "Electronics",
        "items": []
    }]
}

这是我用来访问键值的 jQuery:

$.getJSON('../JSON/cwdata.json', function (cwData) {
    $newData = cwData;        
    $.each($newData, function (key, value) {
        if (key === 'product[0].items[0]') {
            $('#product').append('<li>'+ value +'</li>')
    });
});

“#product”是一个无序列表。

注意:我将 JSON 代码更改为 Salman A 正确回答的代码。

【问题讨论】:

  • 应该是{"this key": "this value"}

标签: jquery json list key key-value


【解决方案1】:

是的,这是可能的。应该是这样的。

"availability": ["six", "five"],

   "connectivity": { "infrared": true,
   "gps" : true 
   }

【讨论】:

  • 感谢您的回答。您能否将键/值更改为我使用的键/值?我似乎越来越糊涂了。您将如何在 jQuery 或 JavaScript 中访问这些键/值?再次感谢。
  • 抱歉回复晚了。正在工作。查看萨尔曼A的答案。他通过 Jquery 正确提供了它。
【解决方案2】:

您的 JSON 无效;数组不能将字符串作为键。它需要看起来像:

{
    "product": {
        "Clothing": {
            "Shirt": "$4.99"
        },
        "Food": {},
        "Electronics": {}
    }
}

或者可能是这样的:

{
    "product": [
        {
            "category": "Clothing",
            "items": [{
                "name": "Shirt",
                "price": "$4.99"
            }]
        }, {
            "category": "Food",
            "items": []
        }, {
            "category": "Electronics",
            "items": []
        }
    ]
}

要迭代此数据,请使用$.each 几个层次:

$.each(cwData.product, function (i, product) {
    console.log(product.category + " (" + product.items.length + " items)");
    $.each(product.items, function (i, item) {
        console.log("\t" + item.name + ": " + item.price);
    });
});
// output:
//
// Clothing (1 items)
//     Shirt: $4.99
// Food (0 items)
// Electronics (0 items) 

【讨论】:

  • 感谢您的回答!我添加了用于访问 JSON 代码(来自另一个文件)的 jQuery,但代码似乎无法正常工作。虽然 JSON 看起来是正确的。
  • 查看修改后的答案。基本上你需要使用$.each 来迭代对象。如果一个项目有子项目,则使用嵌套的$.each
猜你喜欢
  • 2018-04-12
  • 1970-01-01
  • 1970-01-01
  • 2016-03-23
  • 1970-01-01
  • 1970-01-01
  • 2016-04-17
  • 2022-01-24
  • 2020-03-19
相关资源
最近更新 更多