What’s the difference between Javascript Object and JSON object

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

Leave a Comment