Introduction to JSON

JSON stands for JavaScript Object Notation and is a data format meant to store and transfer data. You've seen a format very similar to it any time you've logged JavaScript objects in your console.

You can think of JSON as a string-representation of the data inside a JavaScript object. As such, JSON supports the following values:

  • string
  • number
  • object
  • array
  • boolean
  • null

Here's an example of some JSON containing data about a random fictional person:

JSON
{ "name": "Josh", "weight": 175, "age": 40, "eyecolor": "brown", "cars": [ "Chevy", "Toyota", "Honda" ], "favoriteBook": { "title": "When the Fire Nation Attacked", "author": "Nickelodeon", "released": "02-21-2005" } }

Javascript and JSON work really together thanks to the methods stringify and parse, provided by the JSON object.

These two methods convert a JavaScript object to JSON and back, so no matter which one you have, you can easily generate the other.

Stringify

You can use the stringify method to convert a JavaScript object to JSON.

JAVASCRIPT
const dog = { "name": "Sophie", "age": 3, "weight": 20 } const dogJSON = JSON.stringify(dog); console.log(dogJSON);
HTML
{"name":"Sophie","age":3,"weight":20}

Using stringify on a JavaScript object.

Stringify took the dog JavaScript object and converted it into a string. That string is now valid JSON and can be saved to a file or transferred over the network.

Parse

To get a JavaScript object from JSON, you must parse it, essentially the reverse of using stringify. Using the results we got above, let's parse that JSON and turn it into a JavaScript object:

JAVASCRIPT
const json = '{"name":"Sophie","age":3,"weight":20}'; const dog = JSON.parse(json); console.log(dog);

Parsing JSON into a JavaScript object.

Now that dog is a normal JavaScript object, you can now use it as if it were created without JSON at all.

Resources

Next Lesson »
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.