0

My json object looks like below and i want to loop only 'data'. when i am trying to access with objparse.data , it is throwing null. Please suggest me how to loop the 'data' in objparse object.

objparse =  "{\"success\":true,\"message\":\"\",\"data\":[{\"vehModelCode\":\"0824\",\"vehModelDesc\":\"xA\"},{\"vehModelCode\":\"0825\",\"vehModelDesc\":\"xB\"},]}"
3
  • That's a JSON string, not an object... Commented Oct 11, 2016 at 19:29
  • As objParse is String, so it is throwing null. Try to use : var newObj = eval(objparse); And then use newObj.data. Commented Oct 11, 2016 at 19:29
  • Also consider using $.getJSON() - then have the callback (second argument) accept an argument like responseData and utilize responseData.data... Commented Oct 11, 2016 at 19:30

4 Answers 4

1

Looks like the issue with your example is that the JSON is invalid due to the trailing comma, so passing it to JSON.parse() fails.

..."vehModelDesc\":\"xB\"},]}" should be "vehModelDesc\":\"xB\"}]}" (removed the final comma).

Once that's fixed you can do:

var mydata = JSON.parse(object).data

and then mydata will be an Array type that you can call any of the array methods on (map, forEach, etc.)

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

Comments

0

Check example:

var objparsed =  {"success":true,"message":"","data":[{"vehModelCode":"0824","vehModelDesc":"xA"},{"vehModelCode":"0825","vehModelDesc":"xB"}]};
for (var z in objparsed['data']) {
    console.log(objparsed['data'][z]);
}
var objparse =  '{"success":true,"message":"","data":[{"vehModelCode":"0824","vehModelDesc":"xA"},{"vehModelCode":"0825","vehModelDesc":"xB"}]}';
var result = JSON.parse(objparse);
for (var z in result['data']) {
    console.log(result['data'][z]);
}

Comments

0

You should parse the JSON string first.

var data = JSON.parse(objparse).data;
data.forEach(function(model){
  /* DO STUFF */
});

1 Comment

var data = JSON.parse(objparse).data; throwing as [object][object]
0

I guess you can do as the following code snippet

var objparse =  "{\"success\":true,\"message\":\"\",\"data\":[{\"vehModelCode\":\"0824\",\"vehModelDesc\":\"xA\"},{\"vehModelCode\":\"0825\",\"vehModelDesc\":\"xB\"},]}"
var obj = eval("(" +objparse + ')');
obj.data.forEach(function(model){alert(model);});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Hope this helps

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.