我还是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);
答案 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的信息。