How to Parse JSON in javascript?


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


Asked by:- jaiprakash
0
: 340 At:- 10/12/2017 4:16:42 PM
javascript parse JSON parsing-JSON-in-javascript






2 Answers
profileImage Answered by:- vikas_jk

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

1
At:- 10/13/2017 7:34:13 AM Updated at:- 10/15/2017 8:24:54 AM


profileImage Answered by:- jaya

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

 

1
At:- 10/15/2017 8:23:04 AM





Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly