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 badges2 Answers
Reset to default 5Your "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