Home

Working with JSON

Introduction

JSON, short for JavaScript Object Notation, is a language-independent data format that has been accepted as an industry standard.

Because it is based on the JavaScript programming language, JSON’s syntax looks similar to a JavaScript object with minor differences.

Here is an example JSON object of a person named Kate, who is 30 years old, and whose hobbies include reading, writing, cooking, and playing tennis:

{    "person": {
      "name": "Kate",
      "age": 30,
      "hobbies": [ "reading", "writing", "cooking", "tennis" ]
   }
}


Represented as a JavaScript object literal, the same information would appear as:

{
   person: {
      name: 'Kate',
      age: 30,
      hobbies: [ 'reading', 'writing', 'cooking', 'tennis' ]
   }
}


Reading a JSON String

In a typical web application, the JSON data that we receive from a web request comes in the form of a string.
At other times, JSON data is stored in a file that is used for authentication, configuration, or database storage.
These files typically have a .json extension, and they have to be opened in order to retrieve the JSON string in it.
In either case, we will need to convert the string to a format that we can use in order to access its parts.
Each programming language has its own mechanism to handle this conversion.
In JavaScript, for example, we have a built-in JSON class with a method called .parse() that takes a JSON string as a parameter and returns a JavaScript object.

The following code converts a JSON string object, jsonData, into a JavaScript object, jsObject, and logs jsObject on the console.

const jsonData = '{ "book": {
   "name": "JSON Primer",
   "price": 29.99,
   "inStock": true,
   "rating": null } }';

const jsObject = JSON.parse(jsonData);
console.log(jsObject);


This will print out jsObject as follows:

{
   book: { name: 'JSON Primer', price: 29.99, inStock: true, rating: null }
}

Once we have converted a JSON object to a JavaScript object, we can access the individual properties inside the JavaScript object, for example...

const book = jsObject.book;
console.log(book);
console.log(book.name, book.price, book.inStock);

Which will display...

{ name: 'JSON Primer', price: 29.99, inStock: true, rating: null }
JSON Primer 29.99 true

Top