JSON Object With or Without Quotes

前端 未结 5 378
我寻月下人不归
我寻月下人不归 2020-12-29 12:16

I am trying to learn JSON, i learned that any javascript object with the key in double quotes are considered as JSON object.

And i constructed this object



        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-29 12:49

    You are creating a Javascript Object. If you want a JSON-string from it, use JSON.stringify.

    So

    var myObj = {mykey: "my value"}
       ,myObjJSON = JSON.stringify(myObj);
    

    Based on comments: There is no such thing as a JSON Object. There are JSON-strings, which can be parsed to Javascript Objects. Javascript Objects can be stringified to JSON strings. Within a JSON-string keys and values are quoted. So the result of the above is a string containing '{"mykey":"my value"}'.

    Try parsing myObjJSON in your browser console (using: JSON.parse(myObjJSON)) and you get: Object {mykey: "my value"}.

提交回复
热议问题