JSON Cheat Sheet

What's JSON?

JSON (or JavaScript Object Notation) is an attempt to model reality in a way that can be understood by humans and parsed by many programming languages. In doing so, it brings disparate technologies together such as your database, middleware, and frontend, who can all work with JSON in one form or another.

Quick Links

Objects

Below is an object written in JSON notation. If you're familiar with JavaScript, this shouldn't look too unusual. The primary syntactical difference is that the key must be stored as a string using quotes.

var my_dog = {
  "name":"Greg",
  "breed":"Westie",
  "nicknames":["Mr. Greg", "Gregs"],
  "age":8,
  "height":10,
  "weight":23,
  "photo":"i.imgur.com/j0QxJqy.jpg"
}
			

Accessing Object Properties...

my_dog.namereturns "Greg"
my_dog["breed"]returns "Westie"
my_dog[3]returns 8

Arrays

Below is an array written in JSON notation. Again, this should be familiar.

var my_dog = [
  "Greg",
  "Westie",
  ["Mr. Greg","Gregs"],
  8,
  10,
  23,
  "i.imgur.com/j0QxJqy.jpg"
]
			

Accessing Array Elements...

my_dog[0]returns "Greg"
my_dog[2][0]returns "Mr. Greg"
my_dog[3]returns 8

JSON.stringify()

The stringify method serializes a JavaScript value, converting it to a JSON string. For a detailed explaination of the optional arguments, see stringify()

Here's a simple my_dog object written in JavaScript.

var my_dog = {
  name: "Greg",
	breed: "Westie",
	age: 8
}

dog_string = JSON.stringify(my_dog);

console.log(dog_string);

//The above will have the following console output:
{"name":"Greg","breed":"Westie","age":8}

			

For cleaner output, you can pass a number of spaces as the third argument.

dog_string = JSON.stringify(my_dog, null, 2);

console.log(dog_string);

//The above will have the following console output:

{ "name": "Greg",
  "breed": "Westie",
  "age": 8
}

JSON.parse()

The parse method deserializes a JavaScript value, returning the object corresponding to the given JSON string. For a detailed explaination of the optional arguments, see parse()

Let's return to our original example, the my_dog object written in JSON notation. This time, we'll leave it formatted as it might be when passed as a string.

var my_dog = '{
  "name": "Greg",
  "breed": "Westie",
  "nicknames": ["Mr. Greg", "Gregs"],
  "age": 8,
  "height": 10,
  "weight": 23,
  "photo": "i.imgur.com/j0QxJqy.jpg"
}'
			

As you can see, the value of my_dog is stored as a string and all of the keys are strings.

dog_parsed = JSON.parse(my_dog);

console.log(dog_parsed);

//The above will have the following console output:

{ name: 'Greg',
  breed: 'Westie',
  nicknames: ['Mr. Greg', 'Gregs'],
  age: 8,
  height: 10,
  weight: 23,
  photo: 'i.imgur.com/j0QxJqy.jpg' }