JSON: The Language of Data Transfer

JSON: The Language of Data Transfer
1and1 placeholder image

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:

	
    {
        "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

To use stringify, simply pass in a JavaScript object you want converted to JSON.

	
    var dog = {
      "name": "Sophie",
      "age": 3,
      "weight": 20
    }
    var dogJSON = JSON.stringify(dog);
    console.log(dogJSON);
	
	
    {"name":"Sophie","age":3,"weight":20}
	
Using stringify on a JavaScript object.
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.

1and1 placeholder image

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:

	
    var json = '{"name":"Sophie","age":3,"weight":20}';
    var dog = JSON.parse(json);
    console.log(dog);
	
Parsing JSON into a JavaScript object.
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.