How can I parse JSON string in javascript?
The response is something like
var JSONresponse= [{
"id": 1133,
"name": "Seattle",
"addressLine1": "Test",
"city": "Seattle",
"state": "WA",
"zip": "98115"
}]
How can I get the values of Id, name, city etc from above JSON response using javascript? I know jQuery has $.parseJSON(jsonString), but i don't want to use jQuery, I want javascript solution
Thanks
You can use JSON.Parse in javascript to convert your JSON response into javascript object and then you can access them
var JSONResponse={
"id": 1133,
"name": "Seattle",
"addressLine1": "Test",
"city": "Seattle",
"state": "WA",
"zip": "98115"
}
var obj = JSON.parse(JSON.stringify(JSONResponse));
//then you can access it as
var id=obj.id;
var name =obj.name;
JSON.parse()
is a secure function to parse JSON strings and convert them to objects
There is another way using eval function , so your code will be
var JSONResponse={
"id": 1133,
"name": "Seattle",
"addressLine1": "Test",
"city": "Seattle",
"state": "WA",
"zip": "98115"
}
var jsontext= JSON.stringify(JSONResponse);
var getContact = eval('(' + jsontext + ')');
alert(getContact.name + ", " + getContact.id); // You will get Seattle , 1133
Fiddle here
But as JSON.parse
is secure and fast, i will recommend to use
JSON.parse
function
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly