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

后端 未结 6 1717
灰色年华
灰色年华 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:12

    AFAIK, above is object literal, json as well as javascript object, isn't it?

    It is an object literal. It creates an object.

    It is not JSON, as it doesn't conform to the syntax (which is a subset of object literal notation). The keys are not quoted and the wrong kind of quote marks (' instead of ") are used around the values.

    How do you guys differentiate which is what ?

    Context.

    JSON doesn't usually appear (embedded) in the middle of JavaScript programs. It is a data format and usually appears as whole files (or HTTP responses).

    When something expects an object it could get one from an object literal or from a variable (or a return value from a function call, etc, etc).

提交回复
热议问题