How does JSON.parse() work?

后端 未结 4 1922
渐次进展
渐次进展 2021-02-06 09:03

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 varia

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-06 09:27

    Here is my explanation with a 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, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.

提交回复
热议问题