0

This is my response

["{\"id\":1,\"name\":\"JOHN\"}","{\"id\":2,\"name\":\"MICHEAL\"}"]
var json = JSON.parse(demp);
console.log(json[0].id); says undefined.

How to get id and name ?

Thank you

4 Answers 4

2

There should be no quote arround the {}, otherwise it's not a list of parseable objects, but just a list of strings. This is what your json should look like:

[{"id":1,"name":"JOHN"}, {"id":2,"name":"MICHEAL"}]
Sign up to request clarification or add additional context in comments.

Comments

0

My suggestion is to use a loop to iterate in array as you have suggested in the question.

To me your response is an array so you should JSON.parse() the array instead just var demp:

var DEMP = ["{\"id\":1,\"name\":\"JOHN\"}", "{\"id\":2,\"name\":\"MICHEAL\"}"];
for (var i = 0, syze = DEMP.length; i < syze; i++) {
   var json = JSON.parse(DEMP[i]);
   console.log('Response ID is --> '+json.id + 
               ' Response name is --> ' + json.name);
}

Demo Fiddle

Comments

0
var res                  =   [{"id":1,"name":"JOHN"}, {"id":2,"name":"MICHEAL"}];
var response             =   JSON.stringify(res);
response                 =   JSON.parse(response);
console.log(response[0].id);
console.log(response[0].name);

Comments

0

Iterate over the array and then convert the array values to JSON.

var obj = ["{\"id\":1,\"name\":\"JOHN\"}","{\"id\":2,\"name\":\"MICHEAL\"}"];

for(var i = 0, len = obj.length; i<len;i++) {
   var json = JSON.parse(obj[i]);
   console.log(json.id);
}

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.