What is the difference between a JS object literal and a JSON string?

后端 未结 6 1715
灰色年华
灰色年华 2021-02-04 19:47

I have confusion about what exactly people mean by Object Literals, JSON, JavaScript Objects, to me they seem similar:

{foo: \'bar\', bar : \'baz\'}
6条回答
  •  一生所求
    2021-02-04 20:15

    JSON originates from the object literal notation of JavaScript and itself is a string. That explains the similarity, when just looking at it. Today JSON is used as a general means of serializing all kinds of data, before submitting it over some network or storing it.

    // this is a JSON variable
    var json = '{"foo": "bar", "bar" : "baz"}';
    
    // obj is a JavaScript obj, defined by the object literal on the right hand side
    var obj = {foo: 'bar', bar : 'baz'};
    
    • JSON - serialized object; similar syntax as defining an object in JS
    • Object literal - shorthand syntax to define an object in JS
    • Object - the result of a definition by, e.g., an object literal

    In JS you can convert a JSON string into an object by using

    var obj = JSON.parse( json );
    

    and get the JSON representation of an object (excluding attached functions) by

    var json = JSON.stringify( obj );
    

提交回复
热议问题