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_optio开发者_开发知识库ns":[{"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.
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
精彩评论