Sarfraz
Sarfraz

Reputation: 382696

Javascript JSON.parse or directly access

When we can read a property directly from string:

var data = {"id":1,"name":"abc","address":{"streetName":"cde","streetId":2}};
console.log(data.address.streetName); // cde

Why do people use JSON.parse:

var obj = JSON.parse(data);
console.log(obj.address.streetName); // cde

Upvotes: 1

Views: 166

Answers (3)

Álvaro González
Álvaro González

Reputation: 146430

JSON.parse() expects a string. More specifically, a string with a JSON-encoded piece of data.

If it's applied to an object then it's an error, the source of which is probably the common confusion that seems to exist between JavaScript objects and the JSON format.

Upvotes: 3

Diode
Diode

Reputation: 25135

It is not a string, but Javascript object. String is given below

var data = '{"id":1,"name":"abc","address":{"streetName":"cde","streetId":2}}';

to make it object we use JSON.parse

var obj = JSON.parse(data);
console.log(obj.address.streetName); // cde

Upvotes: 5

Philippe Leybaert
Philippe Leybaert

Reputation: 171764

In your first example, data is an object, but in your second example, data is a JSON string.

That's a major difference. You could call eval(data) to parse a JSON string, but that's very unsafe.

Upvotes: 3

Related Questions