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
You can use JSON.Parse as suggested by other answers, here is example
const employee = `{
"name": "John Wick",
"age": 32,
"city": "New york"
}`;
const employeeObj = JSON.parse(employee);
console.log(employeeObj.name);
// output: John Wick
Json.parse is supported by all major browsers.
You can also use 'eval'
var response = '{"result":true , "count":1}';
var parsedJSON = eval('('+response+')');
var result=parsedJSON.result;
var count=parsedJSON.count;
But since all major browsers now support JSON.parse, we should use it.
You can also check: Read JSON file with Javascript
Thanks.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly