0

how do I access the crop array in this array from javascript? I may have many ids

[{"id":"1","crop":"[{\"class\":\"org.project.Crop\",\"id\":6,\"commonName\":\"Wheat\",\"description\":\"N/A\",\"diseases\":[],\"growing\":\"N/A\",\"harvest\":\"N/A\"}, {\"class\":\"org.project.Crop\",\"id\":5,\"commonName\":\"Sugarcane\",\"description\":\"N/A\",\"diseases\":[],\"growing\":\"N/A\",\"harvest\":\"N/A\"}]]
3
  • maybe you need ... arrayName[0].crop Commented Feb 8, 2013 at 11:47
  • possible duplicate of I have a nested data structure / JSON, how can I access a specific value? Commented Feb 8, 2013 at 11:49
  • If you get this whole response as JSON, then you have a string containing JSON inside JSON, which is very odd. If you are creating this yourself, you should fix the generation process. Commented Feb 8, 2013 at 11:50

3 Answers 3

0

your syntax is wrong, you are missing " and } at the end

here is corrected code:

var data = [{"id":"1","crop":"[{\"class\":\"org.project.Crop\",\"id\":6,\"commonName\":\"Wheat\",\"description\":\"N/A\",\"diseases\":[],\"growing\":\"N/A\",\"harvest\":\"N/A\"}, {\"class\":\"org.project.Crop\",\"id\":5,\"commonName\":\"Sugarcane\",\"description\":\"N/A\",\"diseases\":[],\"growing\":\"N/A\",\"harvest\":\"N/A\"}]"}];
var crop = JSON.parse(data[0].crop);
alert(crop);

online version: http://jsfiddle.net/w38Ku/1/

you have to parse "crop" before you can use it as an object, because you have stored it as a string, not json object

Sign up to request clarification or add additional context in comments.

Comments

0

Maybe use JSON.parse(a["crop"]);

Also have a look at this thread.

Comments

0

You can do:

var x = [{"id":"1","crop":"[{\"class\":\"org.project.Crop\",\"id\":6,\"commonName\":\"Wheat\",\"description\":\"N/A\",\"diseases\":[],\"growing\":\"N/A\",\"harvest\":\"N/A\"}, {\"class\":\"org.project.Crop\",\"id\":5,\"commonName\":\"Sugarcane\",\"description\":\"N/A\",\"diseases\":[],\"growing\":\"N/A\",\"harvest\":\"N/A\"}]];

var crop = JSON.parse(x[0].crop);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.