Deep Diving into JSON and Its Use in JavaScript

Note: This is part 1 of three-part How to Make HTTP Request in JavaScript series. This learning post is still in active development and updated regularly.

When data are exchanged between programs, a browser and server, they are done in simple text. Two such text-based format JSON and XML are commonly used to received data from web servers.

To quote from the MDN Web Docs: “JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa). You’ll come across it quite often, so in this article we give you all you need to work with JSON using JavaScript, including parsing JSON so you can access data within it, and creating JSON.

In this three-part How to Make HTTP Request in JavaScript series, introduction to JSON, working with JSON data, and connecting to external API to obtain JSON data from servers, and their use in web pages will be discussed.

Posts Series:
Part 1: Deep Diving into JSON and Its Use in JavaScript (this post)
Part 2: Working with JSON Data and Common Use Case Examples
Part 3: How to Connect to an External API with JavaScript

The objective of this learning-note post is to discuss basic JSON syntax and working with simple use case example.

What is JSON ? The Basics

The MDN refers JSON (JavaScript Object Notation) as “syntax for serializing objects, arrays, numbers, strings, booleans, and null. It is based upon JavaScript syntax but is distinct from it: some JavaScript is not JSON.

The JSON is used for storing and exchanging data between browser & servers. The JSON data consists of key:value { "key" : "value" } pairs enclosed in curly braces and are saved in a file as .JSON extension. When used inside a html document the JSON data are used as JSON string inside of quotes '{"key":"value"}'.

JSON Data Types & Basic Syntax

Basic JSON syntax is derived from JS object dot notation syntax with key:value pairs separated by commas ( , ) and enclosed in curly brackets { } (in JSON object) or in square brackets [ ] (in JSON array).

The basic syntax of JSON as shown below and full JSON syntax can be found on MDN.

Number: Numbers in JSON must be an integer or a floating point and decimals are not allowed.

#!basic syntax
const jsonObjectName = { string : number_value, ...}

#! example
const myJsonObject = {version: 16.8}

String: JSON strings are written in double quotes ( " ” ).

#!basic syntax
const jsonObjectName = { string : "string value", ...}

#! example
const myJsonObject = {library: 'ES6'}

Boolean: JSON values are written as true/false.

//basic syntax
var jsonObjectName = { string : true/false, ...}

//example
const myJsonObject = {library: 'React', version: 16.8, released: true}

Null: JSON values can be written as null.

//null
null

// example
const x = null;

if(x == 5) {
   document.write("<h1>X is assigned to 5</h1>");
} else {
   document.write("<h1>X is assigned to null</h1>");
}

White Space: Quoting from the MDN Docs, “insignificant whitespace may be present anywhere except within a JSONNumber (numbers must contain no whitespace) or JSONString (where it is interpreted as the corresponding character in the string, or would cause an error)“.

// basic syntax
{string:" ",..}

// example
const objectSpace = {"topic": "React Components"}
const objTopic = {"topic": "ReactState"}

Object: Values in JSON can be an object.

// basic syntax
{ string : value, ...}

//example
{
   "id": "055X",
   "Library": "ReactJs",
   "version": 16.8,
}

Array: Values in JSON can be an array but can’t contain expression, functions, dates and unidentified data types.

// basic syntax
[value, ... ]

//example
{
   "javaScript": [
      { "library":"VueJs" , "version":"v2.6.3" },
      { "library":"reactJs" , "version":"withHooks" },
      { "topic":"ES6" , "topic":"Arrow Function" }
   ]
}

JSON data are enclosed with two curly brackets { } and each key:value entry pair separated by a comma ( , ). JSON data could be written in a single line (shown below) or multi-lines.

"key" : "value", "key" : "value", "key": "value"

An example of multi-line JSON looks line as shown below:

{
  "library" : "ReactJs",
  "version" : "v16.8",
  "withHooks" : true,
  "releaseYear" : 2019
}

Unlike JS objects, JSON keys (left side of colon) require double quotation as in "library" and can be any string. JSON values (right side of colon) also require double quotation except number.

Although JSON syntax resembles JS, it uses text format thus making sending / receiving files between various languages convenient and super easy.

JSON Structure

The JSON data look similar to JS object or JS array but they are JS string. The JSON data can be converted to JS objects and JS objects can be converted to JSON.

To quote from MDN “Converting a string to a native object is called parsing, while converting a native object to a string so it can be transmitted across the network is called stringification.”

Object as JSON

As discussed earlier, JSON object requires double quotes around object key and value.  Single quotes are not valid. It contains properties and not methods. An example of multi-line JSON object discussed earlier:

{
  "name" : "ReactJs",
  "version" : "v16.8",
  "withHooks" : true,
  "releaseYear" : 2019 
}

Additional Information: MDN Web Docs

Accessing Object Value: The JSON object data can be assigned to a variable (eg. myObj) and access its value with dot (.) or bracket [ ]notations.

const myObj = {
  "name" : "ReactJs",
  "version" : "v16.8",
  "withHooks" : true,
  "releaseYear" : 2019 
}
//access with dot notation
console.log(myObj.name);//OUTPUT => ReactJS
console.log(myObj["version"]);//OUTPUT => v16.8

//assign to a variable
const myLib = myObj.name;
const release = myObj["version"];
//console log
console.log(myLib); //OUTPUT => ReactJs
console.log(release); //OUTPUT => v16.8

Functions are NOT allowed in JSON because they can’t be parse by JSON.parse() function. A replacer parameter can be used either a function or an array.

Looping Object Values: JSON objects can be loop through using for loop as shown below.

const myObj = {
  "name" : "ReactJs",
  "version" : "v16.8",
  "withHooks" : true,
  "releaseYear" : 2019
}
 for (x in myObj) {
   console.log(x+ ":  " +(myObj[x]));
   }
//OUTPUT
name:  ReactJs
version:  v16.8
withHooks:  true
releaseYear:  2019
Nested JSON Objects

JSON values can be another JSON object.

//nested JSON objects
{"isbn": "B07N2LFXDP",  
 "author": 
    {
      "firstname": "Robin",
      "lastname": "Wieruch"
    },
  "title": "The Road to React with Firebase",  
  "category": ["Tutorial", "Technology"]
  "release":"Jan, 2019",
  "online": true
 }

Accessing values from JSON nested object with dot (.) or bracket [ ]notations.

//access
console.log(book.author.firstname); //OUTPUT =>Robin
//or
console.log(book.author["firstname"]); //OUTPUT => Robin

JSON Object values can be modified with dot (.) or bracket [ ]notations.

//Modifying value 
book.author.firstname = "John"; //OUTPUT => John 
book.author["firstname"] = "John"; //OUTPUT => John

In the example above, the author.firstname is modified from Robin to john.

Arrays as JSON

JavaScript array and JSON array are similar. Arrays can be value of another object property. In the example below, the tags property contains its value an array data type.

{
"authorName":"Robin Wieruch",
"bookTitle":"The Road to Learn react",
"tags":[ "React", "Library", "JavaScript" ]
}

Accessing Array Value: The JSON array data can be assigned to a variable (eg. myObj) and access its value with using the index number [x] notations.

//define an myObj JSON array object
myObj= {
"authorName":"Robin Wieruch",
"bookTitle":"The Road to Learn react",
"tags":[ "React", "Library", "JavaScript" ]
}
//assign array value to a var
let x= myObj.tags[0];
console.log(x);// OUTPUT => React

Looping through JSON Array: In the above myObj array value can be loop through using for-in loop.

//looping with for..in
for (i in myObj.tags) {
  x = myObj.tags[i];
  console.log(x);
}
//OUTPUT
React
Library
JavaScript

Array Value can be modified (update or delete) using index number [x] notation.

// update array value
myObj.tags[1] = "Framework";
console.log(myObj.tags[1]); //OUTPUT => Framework

//delete array value
delete myObj.tags[1];

In the example above array value of Library is updated to Framework (line 20). Using delete keyword, an array item was deleted (line 24).

Nested JSON Arrays

JSON values in an array can also be another array, or even another JSON object. An example of complex nested JSON array is shown below:

//nested JSON arrays
{ 
  "author_name" : "Robin",
  "author_surname" : "Wieruch",
  "title" : "The Road to learn React",
  "websites" : [ 
    {
      "description" : "rwiruch",
      "URL" : "https://www.robinwieruch.de/"
    },
    {
      "desciption" : "Book",
      "URL" : "https://www.robinwieruch.de/the-road-to-learn-react/"
    }
  ],
  "social_media" : [
    {
      "description" : "twitter",
      "link" : "https://www.twitter.com/rwieruch"
    },
    {
      "description" : "facebook",
      "link" : "https://www.facebook.com/rwieruch"
    },
    {
      "description" : "github",
      "link" : "https://www.github.com/rwieruch"
    }
  ]
}

In the example above, the "websites" and "social_media" key contains nested information enclosed in square brackets [ ].

JSON values in arrays can also be similarly modified with index number [x]notation and deleted with delete keyword.

Looping through an complex nested array value are discussed in Working with JSON Data with Use Case Examples.

JSON vs JavaScript

JSON objects are similar to JavaScript(JS) objects. they are written in key/value pairs enclosed in curly brackets { }. Objects as values in JSON must follow the same rules as JSON objects. An example basic JS object is shown below:

//JS object
{
  Libraries: [
    {
      name: 'ReactJs',
      release: 'v16.8'
    },
    {
      name: 'VueJs',
      release: 'v2.6.5'
    }
  ]
}

The above JS object when converted to JSON, it looks as follows:

{
  "Libraries": [
     {
       "name": "ReactJs",
       "release": "v16.8"
     },
     {
       "name": "VueJs",
       "release": "v2.6.5"
      }
    ]
 }

A key/value pair in JSON object consists of a key name in double quotes (" "), followed by a colon (:), and a value (string, number, object, array, boolean or null) in double quotes except number & null as described earlier.

JSON vs XML

JSON is similar to XML because both are text based but JSON files are shorter and easier to read.

JSON and XML differ because XML has to be parsed with XML parser while JSON can parsed by JS function.

{
  "Libraries": [
    {
     "name": "ReactJs",
     "release": "v16.8"
    },
    {
     "name": "VueJs",
     "release": "v2.6.5"
    }
  ]
 }

Its conversion to XML looks as follows:

<Libraries>
   <name>ReactJs</name>
   <release>v16.8</release>
</Libraries>
<Libraries>
   <name>VueJs</name>
   <release>v2.6.5</release>
</Libraries>

One of the main feature of XML data format is it use of end tags.

JSON Methods

JSON.stringify()

The JSON.stringify() method converts a JavaScript object or value to a JSON string. More discussion on JSON.stringify() are described on this MDN Docs.

An example of stringifying an JS Object:

// Stringly an JS Object
const myObj = {name: "reactJs", version: 16.8, release: 2019}
var myJSON = JSON.stringify(myObj); 
console.log(myJSON);
//OUTPUT
{"name":"reactJs","version":16.8,"release":2019}

An example of stringifying an Array:

//Stringify an JS Array
const myArr = ["ReactJs", 16.8, 2019]
const arrJSON = JSON.stringify(myArr);
console.log(arrJSON);
//OUTPUT
["ReactJs",16.8,2019]
JSON.parse()

The JSON.parse() method parses a JSON string, constructing the JS value or object described by the string.

Parsing an JS Object

Lets say the following JSON string is received from a server:

//JSON string 
'{"name": "reactJs", "version": 16.8, "release": 2019}'

Using JSON.parse() function it can be converted into JS object and stored in a variable myObj as shown below:

//JSON.parse()
const myObj = JSON.parse('{"name": "reactJs", "version": 16.8, "release": 2019}');

Now the myObj can be used as normal JS object.

//console log
console.log(myObj.name); // ReactJs
console.log(myObj.version): // 16.8
Using JSON parse in HTML

The JSON.parse() function can also be used to parse a JSON string received from a server can be used in a HTML page.

<!DOCTYPE html>
<html>
<body>
<p id="root"></p>
<script>
let myObj = '{"name": "ReactJs", "release": "v16.8" }';
myObj = JSON.parse(myObj);

document.getElementById("root").innerHTML =
"Library: " + myObj.name +"<br>" + 
"Version: " + myObj.release;
</script>
</body>
</html>

In the example above, the JSON object string received from a server (discussed in earlier) is directly used in an HTML page which outputs in the browser with same result.

<!-- OUTPUT -->
Library: ReactJs
Version: v16.8
Wrapping Up

In this learning-note post, introduction to JSON basics including its syntax, data types, simple example of JSON as objects or arrays, nested JSON object/arrays were discussed. In the next post in the series working with JSON data with some use case examples will be discussed.

Part 2: Working with JSON Data and Common Use Case Examples

Useful Resources and Links

While preparing this post, I have referred the following references extensively. Please to refer original posts for more detailed information.