最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery - Extract Data from JSON - Stack Overflow

programmeradmin1浏览0评论

I have the following JSON feed:

{"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"}}]}

I am trying to extract the cost of a particular moulding using jQuery .getJSON. My jQuery code is as follows:

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

When this runs I get the following error:

Uncaught TypeError: Cannot read property 'cost' of undefined

Why am I getting this error, many thanks.

I have the following JSON feed:

{"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"}}]}

I am trying to extract the cost of a particular moulding using jQuery .getJSON. My jQuery code is as follows:

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

When this runs I get the following error:

Uncaught TypeError: Cannot read property 'cost' of undefined

Why am I getting this error, many thanks.

Share Improve this question asked Dec 7, 2010 at 23:45 freshestfreshest 6,2419 gold badges37 silver badges38 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Your "mouldings" property of the JSON object is an array of objects. Therefore, the way you'd call it is like this:

alert(data.mouldings[0].moulding_id_2.cost);

If you don't want this to be formatted like this, you'll have to change the way you're formatting your JSON on the server.

To clarify even further, you currently have this:

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

If you want to be able to access your moulding_id_2's cost property like this:

data.mouldings.moulding_id_2.cost

...you'll have to create your JSON like this:

{"mouldings":{"moulding_id_2":{"cost":"3.1","width":45}}

this should do

data.mouldings[0].moulding_id_2.cost
发布评论

评论列表(0)

  1. 暂无评论