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
1
: 2513 At:- 10/12/2017 4:16:42 PM
javascript parse JSON parsing-JSON-in-javascript







3 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

2
At:- 10/13/2017 7:34:13 AM Updated at:- 12/12/2022 7:52:27 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


profileImage Answered by:- jon

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.

0
At:- 12/12/2022 3:48:43 PM Updated at:- 12/12/2022 3:51:48 PM






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