JSON & Javascript Differences

 

JSON looks very similar to Javascript, however, there are subtle differences between the two. The primary differences between the two are:

- JSON requires "keys" to be wrapped with quotes.
- JSON is "dumb" text, not "live" code.

In more detail:

1. A Javscript Object (or Array) is a foundational "thing" that can store values.

2. JSON mimics Javascript in structure -- but it is a string and must be converted (parsed) from a string to an actual Javascript Object.

3. JSON requires field names to be wrapped in double quotes.

4. Javscript Object's don't require field names to be wrapped in quotes... but if they are, it's OK things will still work.

5.When storing JSON within Javascript, the JSON must be wrapped with single quotes because the field names and values are wrapped in double quotes.

6. JSON can be stored pretty much anywhere. Javascript Objects (and Arrays) can not because they only make sense within the context of a script.

 

Here is a simple comparison between a simple Javascript Object and a JSON representation of an Object. Javascript Objects are comma-delimited collections of "value pairs". The overall collection is wrapped with curly brackets.

Javascript Object

{foo:"bar"}

 

Where "foo" is the field name, used to identifiy, or label some kind of data. And "bar" is tha actual value of the field. Together these are refered to as "key-value pairs".

The colon is the signal that the field name and value are directly related to eachother -- similar in functionality to an equal sign (=).

When additional fields are needed, each value-pair set is seperated by a comma.

{foo:"bar", name:"bob"}

 

JSON Object representation

'{"foo" : "bar"}'

 

The JSON representation is very similar in structure, the differences being that "foo" is wrapped with double quotes, and the entire thing is wrapped in single quotes.

 

Javascript Array's may also be represented with JSON. Here's a comparison. Javascript array's are wrapped with brackets, and values are comma delimited.

Javascript Array

[316, true, "foo"]

 

This array contains 3 values.

  • At index 0 (the first item) we have a number (316).
  • At index 1 (the second item) we have a boolean value (true).
  • At index 2 (the thrid item) we have a string ("foo")

 

JSON Array representation

'[316, true, "foo"]'

 

The JSON representation is very similar in structure, the differences being that "foo" the entire thing is wrapped in single quotes.

Numbers and booleans do not require being wrapped in double quotes. They just don't. Don't ask questions, they just don't. Get it? got it? Good.