16 January, 2014 by Denise << programming >>

The difference between JSON and JavaScript

I’ve been doing some interviews at work, and one of the questions I like to ask is “Can you tell me what JSON is?” and I rarely get a satisfying answer. One answer I do hear a lot is that JSON is Javascript, which is not the case. Perhaps this post might help someone understand the differences.

So what is JSON anyway?

JSON is a data-interchange format. If I was explaining it to my mum I’d tell her it’s a language for computers to pass information to each other, in much the same way as us humans use language to communicate with each other.

Some people say JSON is a subset of JavaScript but this isn’t true because JSON allows a couple of unescaped characters (the line separator U+2028 and paragraph separator U+2029) in its strings which ECMA-262 (the JavaScript standard) does not allow.

JSON is independent of the JavaScript language and can be parsed and constructed by/in other languages. Consider it to be a message format.

And what does it look like?

A JSON string can either be in the format of a JSON array:

[ {"pet" : "cat", "colour" : "brown"}, {"pet" : "rabbit", "colour" : "white"} ]

or a JSON object:

{"petList" : [
{"pet" : "cat", "colour" : "brown"}, {"pet" : "rabbit", "colour" : "white"}
] }

Note that these two formats are being used to store the same data in the same structure, it’s just that the second example is wrapping the array in a JSON object. However, returning an array may expose you to security vulnerabilities: see this blog post for more details, so take this into account if you have the luxury of designing the message format.

Some rules for valid JSON include:

keys must be strings enclosed in double quotes
values can be strings, numbers, JSON objects, arrays, true, false, or null.

Values can’t be functions.

Contrast this to a JavaScript object literal then which can look like the following:

{ petList: [ {pet : "cat", colour : "brown"} ] , numberOfPets : function() { return 1;} }

You can see that the value of the key ‘numberOfPets’ can be a function, and that none of the keys in the object literal are strings.

For further info and a great visual reference of JSON syntax, see http://json.org/.