parsing JSON in nodejs

后端 未结 2 1017
死守一世寂寞
死守一世寂寞 2021-01-01 02:08

Hi i have the below json

{id:\"12\",data:\"123556\",details:{\"name\":\"alan\",\"age\":\"12\"}}

i used the code below to parse



        
2条回答
  •  天命终不由人
    2021-01-01 03:09

    If you already have an object, you don't need to parse it.

    var chunk={id:"12",data:"123556",details:{"name":"alan","age":"12"}};
    // chunk is already an object!
    
    console.log(chunk.details);
    // => {"name":"alan","age":"12"}
    
    console.log(chunk.details.name);
    //=> "alan"
    

    You only use JSON.parse() when dealing with an actual json string. For example:

    var str = '{"foo": "bar"}';
    console.log(str.foo);
    //=> undefined
    
    // parse str into an object
    var obj = JSON.parse(str);
    
    console.log(obj.foo);
    //=> "bar" 
    

    See json.org for more details

提交回复
热议问题