AppDividend
Latest Code Tutorials

How To Parse JSON in Javascript

1,431

Get real time updates directly on you device, subscribe now.

In this example, we will see How To Parse JSON in Javascript. 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. If you have JSON data as part of a string, the best way to parse it is by using the JSON.parse() method. 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.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Join the program

#How To Parse JSON in Javascript

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

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.

You can process the JSON asynchronously by wrapping it in a promise and a setTimeout call, which makes sure 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 Node.js in your machine.

// 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 run 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.js. Then 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.

#Deal with JSON Files.

Let us assume that we have 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);

#JSON.stringify

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

Related Posts
1 of 17

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 like below.

JavaScript JSON parse() Method

 

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

You can also read the file asynchronously using fs.readFile, and this is the best option. In this case, the file content is provided as a callback, and inside the callback, you can process the JSON. Write the following code inside the 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.

Finally, How To Parse JSON in Javascript tutorial is over. Thanks for taking.

Leave A Reply

Your email address will not be published.

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