What Are the Differences Between JSON and JavaScript Object

What are the differences between JSON and JavaScript object?

First you should know what JSON is:

  • It is language agnostic data-interchange format.

The syntax of JSON was inspired by the JavaScript Object Literal notation, but there are differences between them.

For example, in JSON all keys must be quoted, while in object literals this is not necessary:

// JSON:
{ "foo": "bar" }

// Object literal:
var o = { foo: "bar" };

The quotes are mandatory on JSON because in JavaScript (more exactly in ECMAScript 3rd. Edition), the usage of reserved words as property names is disallowed, for example:

var o = { if: "foo" }; // SyntaxError in ES3

While, using a string literal as a property name (quoting the property name) gives no problems:

var o = { "if": "foo" }; 

So for "compatibility" (and easy eval'ing maybe?) the quotes are mandatory.

The data types in JSON are also restricted to the following values:

  • string
  • number
  • object
  • array
  • A literal as:

    • true
    • false
    • null

The grammar of Strings changes. They have to be delimited by double quotes, while in JavaScript, you can use single or double quotes interchangeably.

// Invalid JSON:
{ "foo": 'bar' }

The accepted JSON grammar of Numbers also changes, in JavaScript you can use Hexadecimal Literals, for example 0xFF, or (the infamous) Octal Literals e.g. 010. In JSON you can use only Decimal Literals.

// Invalid JSON:
{ "foo": 0xFF }

There are some buggy implementations (Firefox 3.5+, IE8+, json2.js) where octal literals are wrongly allowed, e.g. JSON.parse('01') should produce a SyntaxError.

What is the difference between JSON and Object Literal Notation?

Lets clarify first what JSON actually is. JSON is a textual, language-independent data-exchange format, much like XML, CSV or YAML.

Data can be stored in many ways, but if it should be stored in a text file and be readable by a computer, it needs to follow some structure. JSON is one of the many formats that define such a structure.

Such formats are typically language-independent, meaning they can be processed by Java, Python, JavaScript, PHP, you name it.

In contrast, JavaScript is a programming language. Of course JavaScript also provides a way to define/describe data, but the syntax is very specific to JavaScript.

As a counter example, Python has the concept of tuples, their syntax is (x, y). JavaScript doesn't have something like this.


Lets look at the syntactical differences between JSON and JavaScript object literals.

JSON has the following syntactical constraints:

  • Object keys must be strings (i.e. a character sequence enclosed in double quotes ").
  • The values can be either:

    • a string
    • a number
    • an (JSON) object
    • an array
    • true
    • false
    • null
  • Duplicate keys ({"foo":"bar","foo":"baz"}) produce undefined, implementation-specific results; the JSON specification specifically does not define their semantics

In JavaScript, object literals can have

  • String literals, number literals or identifier names as keys (since ES6, keys can now also be computed, which introduces yet another syntax).
  • The values can be any valid JavaScript expression, including function definitions and undefined.
  • Duplicate keys produce defined, specified results (in loose mode, the latter definition replaces the former; in strict mode, it's an error).

Knowing that, just by looking at the syntax, your example is not JSON because of two reasons:

  1. Your keys are not strings (literals). They are identifier names.
  2. You cannot assign a function as a value to a "JSON object" (because JSON doesn't define any syntax for functions).

But most importantly, to repeat my explanation from the beginning: You are in a JavaScript context. You define a JavaScript object. If any, a "JSON object" can only be contained in a string:

 var obj = {foo: 42}; // creates a JavaScript object (this is *not* JSON)
var json = '{"foo": 452}'; // creates a string containing JSON

That is, if you're writing JavaScript source code, and not dealing with a string, you're not dealing with JSON. Maybe you received the data as JSON (e.g., via ajax or reading from a file), but once you or a library you're using has parsed it, it's not JSON anymore.


Only because object literals and JSON look similar, it does not mean that you can name them interchangeably. See also There's no such thing as a "JSON Object".

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

Javascript object Vs JSON


  1. Is the key/property name valid both with/without quotes ?

The only time you need to enclose a key in quotes when using Object Literal notation is where the key is a reserved word or contains a special character (if, :, - etc). It is worth noting that a key in JSON must be enclosed in double quotes.



  1. If I convert the above object to JSON using var jSonString = JSON.stringify(testObject);, what is the difference between the 2 (JS obj and JSON)?

JSON is a data interchange format. It's a standard which describes how ordered lists and unordered maps, strings, booleans and numbers can be represented in a string. Just like XML and YAML is a way to pass structured information between languages, JSON is the same. A JavaScript object on the other hand is a physical type. Just like a PHP array, a C++ class/ struct, a JavaScript object is a type internal to JavaScript.

Here's a story. Let's imagine you've purchased some furniture from a store, and you want it delivered. However the only one left in stock is the display model, but you agree to buy it.

In the shop, the chest-of-drawers you've purchased is a living object:

    var chestOfDrawers = {
color: "red",
numberOfDrawers: 4
}

However, you can't send a chest-of-drawers in the post, so you dismantle it (read, stringify it). It's now useless in terms of furniture. It is now JSON. Its in flat pack form.

    {"color":"red","numberOfDrawers":4}

When you receive it, you then rebuild the chest-of-drawers (read, parse it). Its now back in object form.

The reason behind JSON, XML and YAML is to enable data to be transferred between programming languages in a format both participating languages can understand; you can't give PHP or C++ your JavaScript object directly; because each language represents an object differently under-the-hood. However, because we've stringified the object into JSON notation; i.e. a standardised way to represent data, we can transmit the JSON representation of the object to another language (C++, PHP), they can recreate the JavaScript object we had into their own object based on the JSON representation of the object.

It is important to note that JSON cannot represent functions or dates. If you attempt to stringify an object with a function member, the function will be omitted from the JSON representation. A date will be converted to a string;

    JSON.stringify({
foo: new Date(),
blah: function () {
alert('hello');
}
}); // returns the string "{"foo":"2011-11-28T10:21:33.939Z"}"


  1. For parsing a JSON string, is the method below recommended? var javascriptObj = JSON.parse(jSonString);

Yes, but older browsers don't support JSON natively (IE <8). To support these, you should include json2.js.

If you're using jQuery, you can call jQuery.parseJSON(), which will use JSON.parse() under the hood if it's supported and will otherwise fallback to a custom implementation to parse the input.

What are the differences between using JSON arrays vs JSON objects?

The difference between an array and an object is that

Objects are set up using a key and value like:

person.age = 15;

If the key value is a variable, then one could access it like:

var key = "age";
alert(person[key]);

Arrays use an integer[1] index and take a value.

player[1].score += 1000;

[1] Yes, I know, in JavaScript the integer index is really turned into a string behind the scenes. Ignore that. Think of arrays taking an integer value ESPECIALLY when you think of JSON.

What is the difference between a JSON object and a JSON document?

What you are looking at has nothing to do with JSON. This is simply how Chrome displays objects in the console.

The leading name (Document, Object) indicates the type of the object. Chrome will determine this type based on certain heuristics (which I don't know).

Maybe the objects have different prototypes, and that's why it shows a different type name.

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

JSON is a just a data format, like XML. True JSON should have the keys surrounded by double quotes, like so:

{"foo":"bar"}

JavaScript Objects are part of the JavaScript language, and have associated things such as a prototype.

Object literals is creating a javascript object in place with brackets as opposed to using the new keyword, or Object.create().

//object literal
var foo = {};

//equivalent
var foo = new Object();

Compare two JSON objects and just return another JSON object with only the changes

You can try following as a simple comparison:

Note: This answer assumes the structure to be exactly same. You can take this as reference and make it more generic for cases where structures are different.

Points to consider:

  • Number of items are different. o1.details have 2 entries and o2.details have say 5 entries.
  • Object structure is different. Properties in both object are different.

function getDifference(o1, o2) {  var diff = {};  var tmp = null;  if (JSON.stringify(o1) === JSON.stringify(o2)) return;
for (var k in o1) { if (Array.isArray(o1[k]) && Array.isArray(o2[k])) { tmp = o1[k].reduce(function(p, c, i) { var _t = getDifference(c, o2[k][i]); if (_t) p.push(_t); return p; }, []); if (Object.keys(tmp).length > 0) diff[k] = tmp; } else if (typeof(o1[k]) === "object" && typeof(o2[k]) === "object") { tmp = getDifference(o1[k], o2[k]); if (tmp && Object.keys(tmp) > 0) diff[k] = tmp; } else if (o1[k] !== o2[k]) { diff[k] = o2[k] } } return diff;}
var o1={id:"1",details:[{name:"Peter",address:"Arizona",phone:9900998899},{name:"Jam",address:"Kentucky",phone:56034033343}],profession:"Business"},o2={id:"2",details:[{name:"Peter",address:"Arizona",phone:9900998899},{name:"David",address:"Boston",phone:434323434}],profession:"Business"};
var d = getDifference(o1, o2)console.log(d)


Related Topics



Leave a reply



Submit