JSON Syntax and Tips

Sam Deering
Share

Back to basics: Quick Recap on What is JSON.

JavaScript Object Notation (JSON) is a text format for the serialization of structured data. It is derived from the object literals of JavaScript

JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).

JSON Simple Object Examples

This is a JSON object with properties:

{
"myObject":
{
"name":"obi wan kenobi",
"weapons":"lightsaber",
"specialPowers":"the force"
}
}
[/code

[code lang="js"]
This is a JSON object which contains
{
"Africa":{

}

JSON Simple Array Examples

This is a JSON Object containing a JSON array:

{
"myObject":
{
"name":"obi wan kenobi",
"weapons": ["lightsaber","smoke grenade","knife","jedi things"],
"specialPowers":"the force"
}
}

This is a JSON array containing two objects:

{
"africaLagos": [
{
"from": -377711769600000,
"to": -1588464816000,
"dst": false,
"offset": 816,
"name": "LMT"
},
{
"from": -1588464816000,
"to": 253402300799000,
"dst": false,
"offset": 3600,
"name": "WAT"
}
]
}

More JSON Examples

Some tips working with JSON:

  • Whitespace (Space, Horizontal tab, Line feed or New line or Carriage return) does not matter in JSON. It can also be minified with no affect to the data.
  • Object literal names MUST be lowercase (ie – null, false, true etc).
  • Keep all name and value pairs in quotes to aviod
  • Validate your JSON before using it – http://www.jsonlint.com
  • The default unicode encoding for JSON is UTF-8 (see all Application Media Types http://www.iana.org/assignments/media-types/application/index.html)
  • The MIME media type for JSON text is application/json (type and subtype respectively). further reading: Multipurpose Internet Mail Extensions (MIME) http://en.wikipedia.org/wiki/MIME

Parsing JSON in

It’s not recommended to blindly evaluate any JSON string with eval() because of the security implications. It’s best if you use the JSON.parse() method, which is part of the language since ES5 and is natively provided by the Javascript engines in modern browsers.

In jQuery, there’s the parseJSON() method:

// an input JSON string
var jstr = '{"mykey": "my value"}';
var data = jQuery.parseJSON(jstr);
console.log(data.mykey); // "my value"

The opposite of JSON.parse() method is JSON.stringify(). It takes any object or array (or a primitive) and serializes it into a JSON string.

var dog = {
name: "Fido",
dob: new Date(),
legs: [1, 2, 3, 4]
};
var jsonstr = JSON.stringify(dog);
// jsonstr is now:
// {"name":"Fido","dob":"2010-04-11T22:36:22.436Z","legs":[1,2,3,4]}

Characters that must be escaped in JSON strings

  • quotation mark “
  • forward slash /
  • back slash \
  • new line n
  • carriage return r
  • tab t