How does JSON.parse () work?

I have not worked too much on javascript. And I need to parse a JSON string. So, I want to know what exactly JSON.parse does. For example: If I assign a json string to a variable like this,

var ab = {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}};

Now when I type 'ab', I get the object.

Similarly, when I do this:

var pq = '{"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}}';
var rs = JSON.parse(pq);

"rs" is the same object as "ab". So what is the difference in the two approaches and what makes JSON.parse different?

This may be a dumb question. But it would be helpful if anyone could explain this.

Thanks.

+4
source share
4 answers

A Javascript object is a data type in Javascript - it has a couple of properties and values, as you defined in the first example.

var ab = {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}};

Json: JSON - - , ( )

var pq = '{"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}}';

json.

, , JSON.parse() , JSON.

+5

jsfiddle.

//this is already a valid javascript object
//no need for you to use JSON.parse()
var obj1 = {"name":"abcd", "details":"1234"};
console.log(obj1);

//assume you want to pass a json* in your code with an ajax request
//you will receive a string formatted like a javascript object
var str1 = '{"name":"abcd", "details":"1234"}';
console.log(str1);

//in your code you probably want to treat it as an object
//so in order to do so you will use JSON.parse(), which will
//parse the string into a javascript object
var obj2 = JSON.parse(str1);
console.log(obj2);

JSON JavaScript Object Notation - , . - XML.

+3

'ab' , javascript, {} . "", .

+1

!! . ab , pq - (). - , "" . , -. , , . pq , : { "name": "abcd", "details": { "address": "pqrst", "Phone": 1234567890}} , , , , 66. ab , .

JSON.parse() -, () . . { "name": "abc" JSON.parse .

pq . - pq.name, undefined. JSON.parse(), rs.name "abcd". rs , . rs.length, undefined.

0

Source: https://habr.com/ru/post/1608431/


All Articles