Reputation: 109
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
Upvotes: 0
Views: 2128
Reputation: 74738
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);
}
Upvotes: 0
Reputation: 8346
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);
}
Upvotes: 0
Reputation: 11984
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);
Upvotes: 0
Reputation: 8263
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"}]
Upvotes: 2