AppDividend
Latest Code Tutorials

Javascript parse json | How To Parse JSON in Javascript

1

Javascript json parse() is an inbuilt function that converts text into a Javascript object.  The json parse() function is converting json string to object. The JSON.parse() is synchronous, so the more the JSON data is big, the more time your program execution will be blocked until the JSON is finished parsing. If you have JSON data as part of the string, the best way to parse it is by using the JSON.parse() method.

The primary use of JSON is to exchange data between client and server. When we receive the data from a web server, the data is always a string, so we need to parse the data with JSON.parse(), and the data becomes a JavaScript object.

#What is JSON(Javascript Object Notation)

JSON is derived from the JavaScript programming language, and it is the natural choice to use as the data format in JavaScript. For example when we create and consume API for mobile and other applications.

JSON stands for JavaScript Object Notation, which is usually pronounced like the name “Jason”.

If you want to begin thinking about where you may use the JSON in your JavaScript projects, some general use cases of JSON include:

  1. Storing the data.
  2. Generating data structures from user input.
  3. Transferring the data from client to server, server to server, and server to a client.
  4. Configuring and verifying the data.

#JSON Format

JSON’s format is derived from JavaScript object syntax, but it is entirely text-based.

It is a key-value data format which is typically rendered in curly braces.

When you’re working with JSON, you will likely see the JSON objects in the .json file, but they can also exist as the JSON object or string within the context of the program.

See the following syntax.

{ 
  "character_name"  :  "Eleven", 
  "actor_name"      :  "Millie Bobby Brown", 
  "age"             :  "15" 
}

You can validate the JSON syntax here.

You may see JSON as a string rather than an object within the context of a JavaScript program file or script. In this case, you may also see it all on one line.

let stranger =  '{ "character_name" : "Eleven", "actor_name" : "Millie Bobby Brown", "age" : "15" }'

Javascript JSON parse

We will take an example and understand how this works.

Let us assume that we received the following text from a web server:

'{ "name":"Krunal", "age":25, "city":"Rajkot", "degree": "BE"}'

Now use the function JSON.parse() to convert text into a JavaScript object.

let obj = JSON.parse('{ "name":"Krunal", "age":25, "city":"Rajkot", "degree": "BE"}');

So, the whole string becomes a JS object now, and we can access its values by its properties.

console.log(obj.degree); // BE

It was the primary example of Parse JSON in Javascript.

#Exceptions in JSON

Date objects are not allowed in JSON.

If you need to include a date, you need to write it as a string.

let birth = '{ "birthDate":"1993-09-10"}';
let obj = JSON.parse(birth);
obj.birthDate = new Date(obj.birthDate);

console.log(obj.birthDate); //1993-09-10T00:00:00.000Z

#Asynchronous Function in Javascript

You can check out my async-await guide if you do not know what is an asynchronous function in javascript.

You can process the JSON asynchronously by wrapping it inside the promise and the setTimeout call, which makes sure that the parsing takes place in the next iteration of the event loop.

For this example, we are using Node.js for an explanation. So create one file called server.js and add the following code inside it.

You need to have installed the Node.js on your machine to execute the javascript programs.

// server.js

const parseJsonAsyncFunc = jsonString => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(JSON.parse(jsonString));
    });
  });
}

let data = '{ "name":"Krunal", "age":25, "city":"Rajkot", "degree": "BE" }';
parseJsonAsyncFunc(data).then(jsonData => console.log(jsonData.degree));

Now, go to the terminal and execute the following command.

node server

How To Parse JSON in Javascript

So, we have used the Promise to process JSON Asynchronously.

#Async-Await in JavaScript

If we do not want to use Promise, then we can use async-await in Node.jsThen our example looks like below. The output remains the same, but we are not using Promise.

// server.js

async function parseJsonAsyncFunc(jsonString) {
  const obj = await JSON.parse(jsonString);
  console.log(obj.degree);
}

let data = '{ "name":"Krunal", "age":25, "city":"Rajkot", "degree": "BE" }';
parseJsonAsyncFunc(data);

You can find out more about async-await on this link.

#Working with JSON Files.

Let us assume that we have a JSON file with the following content.

{
  "data":[
    {
      "name":"Krunal", 
      "age":25, 
      "city":"Rajkot", 
      "degree": "BE"
    },
    {
      "name":"Ankit", 
      "age":23, 
      "city":"Rajkot", 
      "degree": "MCA"
    },
    {
      "name":"Nehal", 
      "age":30, 
      "city":"Rajkot", 
      "degree": "BE"
    }
  ]
}

Let us name it data.json. Now, we can efficiently use this file in the Node.js application by requiring it. So write the following code inside a server.js file.

Here, JSON.parse has nothing to do with it, but I want to let you know guys that we can require any JSON file in our Node.js application and use it as a standard Javascript object.

// server.js

let dataFile = require('./data.json');
console.log(dataFile.data[0].degree);

#Parse nested JSON in JavaScript

JSON objects and arrays can also be nested.

The JSON object can arbitrarily contain other JSON objects, arrays, nested arrays, arrays of JSON objects, and so on.

The below example will show you how to parse the nested JSON object and extract all the values in JavaScript.

// app.js

let shows = `{
  "netflix": {
      "name": "Stranger Things",
      "creator": "Duffer Brothers",
      "year": 2016,
      "characters": ["Eleven", "Mike", "Dustin"],
      "genre": "Science Fiction/Horror",
      "price": {
          "1 person": "$5", "2 person": "$8", "4 person": "$13"
      }
  }
}`;

// Converting JSON object to JS object
let obj = JSON.parse(shows);

// Define recursive function to print nested values
function printValues(obj) {
  for(let k in obj) {
      if(obj[k] instanceof Object) {
          printValues(obj[k]);
      } else {
         console.log(obj[k]);
      };
  }
};

// Printing all the values from the resulting object
printValues(obj);

See the output.

➜  es git:(master) ✗ node app
Stranger Things
Duffer Brothers
2016
Eleven
Mike
Dustin
Science Fiction/Horror
$5
$8
$13
➜  es git:(master) ✗

#JSON.stringify

JSON.parse() function will convert the String into the Javascript object.

JSON.stringify() function will convert the Javascript Object into the String.

// server.js

let dataFile = require('./data.json');
let stringData = JSON.stringify(dataFile);
console.log(stringData);

PARSING JSON WITH NODE

So, it has converted the whole Javascript Object into the String.

#FileSystem In Node.js

Write the following code inside the server.js file.

// server.js

const fs = require('fs');
const fileContents = fs.readFileSync('./data.json', 'utf8');

try {
  const data = JSON.parse(fileContents)
  console.log(data);
} catch(err) {
  console.error(err);
}

You can find the output below.

JavaScript JSON parse() Method

In the above example, the Node.js system reads the file synchronously.

You can also read a file asynchronously using fs.readFile, and it is the best option.

In this case, the file content is provided as the callback, and inside the callback, you can process the JSON.

Write the following code inside a server.js file.

// server.js

const fs = require('fs');

fs.readFile('./data.json', 'utf8', (err, fileContents) => {
  if (err) {
    console.error(err)
    return;
  }
  try {
    const data = JSON.parse(fileContents)
    console.log(data);
  } catch(err) {
    console.error(err);
  }
})

Here also, we get the same output.

#Stringify a JavaScript Array

You can convert the JavaScript arrays to JSON strings, like the following.

// app.js

let arr = ["Millie", "Gaten", "Finn", "Caleb", "Noah"];

// Converting JS array to JSON string
let json = JSON.stringify(arr);
console.log(json);

See the output.

➜  es git:(master) ✗ node app
["Millie","Gaten","Finn","Caleb","Noah"]
➜  es git:(master) ✗

#Javascript JSON parse array

Let’s say, and you have the following data.

data = `{
  "success": true,
  "apps": [
    {
      "app_name": "FB",
      "app_type": "Social Network",
      "app_unit": "1"
    },
    {
      "app_name": "Paypal",
      "app_type": "Payment",
      "app_unit": "2"
    },
    {
      "app_name": "Netflix",
      "app_type": "Media",
      "app_unit": "3"
    }]
}`

Now, we need to parse that array using JSON.parse() function.

See the following code.

// app.js

data = `{
  "success": true,
  "apps": [
    {
      "app_name": "FB",
      "app_type": "Social Network",
      "app_unit": "1"
    },
    {
      "app_name": "Paypal",
      "app_type": "Payment",
      "app_unit": "2"
    },
    {
      "app_name": "Netflix",
      "app_type": "Media",
      "app_unit": "3"
    }]
}`

let jsonData = JSON.parse(data);
for (let i = 0; i < jsonData.apps.length; i++) {
  let app = jsonData.apps[i];
  console.log(app.app_name);
}

See the output.

➜  es git:(master) ✗ node app
FB
Paypal
Netflix
➜  es git:(master) ✗

Finally, Javascript parse json | How To Parse JSON in Javascript is over.

Recommended Posts

Javascript Object.keys()

Javascript Object.values()

Javascript Object.assign()

Javascript Object.create()

Javascript Object.freeze()

1 Comment
  1. Cristiano De Vinni says

    Really nice tutorial dude !

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.