引用JSON数组的麻烦

时间:2013-08-13 14:25:52

标签: javascript arrays json object reference

我还是JSON的新手,所以我有一个非常愚蠢的问题。我如何参考
list.data[0].bom-item.descriptor?我创建的警报声明对我不起作用。谢谢你的帮助。

var txt='{"list": {"data": [{"bom-item": {"dmsID": 3949,"bomPath": "3951B3949","workspaceType": 6,"workspaceID": 8,"bomDepthLevel": 1,"quantity": 1,"formattedQuantity": "1.0","descriptor": "500-0059-000 - FCI, P681-C01 SKU77 (900-60681-0077-400) [REV:D]","revision": "D","units": "EA","itemNumber": 1,"assembly": false,"cost": 0,"isPinned": false,"quoteID": 0,"isUsingDefaultQuote": false,"leaf": false,"redlinedCost": -1,"redlineAddition": false,"redlineAgainstVersion": -1,"redlineDeletion": false,"totalWeight": 1,"lifecycleStatus": "Production","hasSourcing": false,"fields": null}}]}}'



alert(txt.list.data[0].bom-item.descriptor);

2 个答案:

答案 0 :(得分:1)

bom-item不是合法的Javascript标识符。

相反,您需要使用索引符号:

txt.list.data[0]["bom-item"].descriptor

或者,更好的是,改用camelCase。

答案 1 :(得分:1)

在当前代码中,txt只是一个字符串,因此它没有JSON对象属性。您需要使用JSON.parse()将其转换为JSON对象(并使用另一个答案中所述的索引表示法 - 连字符-导致问题):

<  yourObj = JSON.parse('{"list": {"data": [{"bom-item": {"dmsID": 3949,"bomPath": "3951B3949","workspaceType": 6,"workspaceID": 8,"bomDepthLevel": 1,"quantity": 1,"formattedQuantity": "1.0","descriptor": "500-0059-000 - FCI, P681-C01 SKU77 (900-60681-0077-400) [REV:D]","revision": "D","units": "EA","itemNumber": 1,"assembly": false,"cost": 0,"isPinned": false,"quoteID": 0,"isUsingDefaultQuote": false,"leaf": false,"redlinedCost": -1,"redlineAddition": false,"redlineAgainstVersion": -1,"redlineDeletion": false,"totalWeight": 1,"lifecycleStatus": "Production","hasSourcing": false,"fields": null}}]}}')
>  [object Object]
<  yourObj.list.data[0]["bom-item"].descriptor
>  "500-0059-000 - FCI, P681-C01 SKU77 (900-60681-0077-400) [REV:D]"

有关JSON对象at MDN的信息。