jQuery - 从JSON中提取数据

fre*_*est 1 javascript jquery json

我有以下JSON提要:

{"mouldings":[{"moulding_id_2":{"cost":"3.1","width":45}},{"moulding_id_4":{"cost":"1.5","width":30}},{"moulding_id_6":{"cost":"2.1","width":50}}],"material_costs":[{"mountboard":{"cost":"0.00000246494303242769"}},{"glass":{"cost":"0.0000032426589803639"}},{"backing_board":{"cost":"0.00000135110790848496"}}],"app_options":[{"vat":{"value":"17.5"}},{"wastage":{"value":"20"}},{"markup":{"value":"3"}}]}
Run Code Online (Sandbox Code Playgroud)

我试图使用jQuery .getJSON来提取特定成型的成本.我的jQuery代码如下:

$.getJSON( '/calculate_quote/2,6,4.json', function (data) {
  alert(data.mouldings.moulding_id_2.cost);
});
Run Code Online (Sandbox Code Playgroud)

当这运行时,我收到以下错误:

Uncaught TypeError: Cannot read property 'cost' of undefined
Run Code Online (Sandbox Code Playgroud)

为什么我会收到此错误,非常感谢.

tre*_*ace 5

JSON对象的"模拟"属性是一个对象数组.因此,你打电话的方式是这样的:

alert(data.mouldings[0].moulding_id_2.cost);
Run Code Online (Sandbox Code Playgroud)

如果您不希望这样格式化,则必须更改在服务器上格式化JSON的方式.

为了进一步澄清,您目前有这样的:

{" moldings ":[ {"moulding_id_2":{"cost":"3.1","width":45}} ]

如果您希望能够访问moulding_id_2的成本属性,请执行以下操作:

data.mouldings.moulding_id_2.cost
Run Code Online (Sandbox Code Playgroud)

...你必须像这样创建你的JSON:

{ "模制品":{ "moulding_id_2":{ "成本": "3.1", "宽度":45}}