What's the difference between Javascript Object and JSON object

前端 未结 5 1476
南笙
南笙 2020-11-27 02:55

Can anyone tell me the difference between Javascript Object and JSON object with an example?

5条回答
  •  醉酒成梦
    2020-11-27 03:13

    A Javascript object is a data type in Javascript - it makes sense only in Javascript. Often you see a Javascript object literal like this:

    var obj = {
        a: 1,
        b: 2
    };
    

    A JSON string is a data interchange format - it is nothing more than a bunch of characters formatted a particular way (in order for different programs to communicate with each other). Because of this, it can exist inside Javascript, or in another language or simply stored inside a database or a text file.

    The above Javascript object can be represented in the JSON format in Javascript like this:

    var json = '{ "a": 1, "b": 2 }';
    

    Or in C# like this:

    string json = "{ \"a\": 1, \"b\": 2 }";
    

    As you can see, a JSON is simply stored inside a string. To make it useful, the JSON string can be parsed to produce an object in any language. Because the JSON format mimics Javascript's object literal syntax, Javascript makes the parsing process easy:

    var obj = eval('(' + json + ')');
    

    Though typically you'd see:

    var obj = JSON.parse(json); // for security reasons
    

    Note that JSON is limited in that it cannot store functions - the only values it can contain are:

    • objects (literals)
    • arrays
    • numbers
    • booleans
    • strings
    • nulls

提交回复
热议问题