Working with JSON in JavaScript


Earlier we understood the basics of JSON, Its data types, and how to create JSON objects. Now we will see how to work with JSON in JavaScript.

JSON is used to send and receive data from a server. It is supported by all the major browsers and you can work with any modern programming language with JSON, like JavaScript, PHP, Python, Java, etc.

In this tutorial, we will see how to work with JSON in JavaScript.

Without wasting any time in the introduction, let's get started.

working with JSON in JavaScript

JSON in JavaScript

JSON was derived from JavaScript. So, it is very easy to work with JSON in JavaScript.

JavaScript has a built-in object called JSON which provides 2 major methods to work with JSON.

  1. JSON.stringify() - Converts a JavaScript object into a JSON string.
  2. JSON.parse() - Converts a JSON string into a JavaScript object.

Let's see how to use these methods.


1. JSON.stringify()

The JSON.stringify() method converts a JavaScript object into a JSON string.

Use: This method is used when you have some data in the form of a JavaScript object and you want to send it to the server. In this case, you need to convert the JavaScript object into a JSON string and send it to the server.

Syntax:

JSON.stringify(object)

Here, the object is the JavaScript object you want to convert into a JSON string.

Example

Stringify a JavaScript object into a JSON string.

let student = {
  "name": "Alice",
  "major": "Computer Science",
  "age": 20
};

let studentJSON = JSON.stringify(student);
console.log(studentJSON);

// checking the type of studentJSON
console.log(typeof studentJSON);

Now your JavaScript object is converted into a JSON string. You can use this JSON string and send it to the server.


2. JSON.parse()

The JSON.parse() method converts a JSON string into a JavaScript object.

Use: Just like we send data to the server in the form of JSON string, we also receive data from the server in the same form. In this case, we need to convert the received into a JavaScript object so that we can use it in our program.

For this purpose, we use the JSON.parse() method.

Syntax:

JSON.parse(jsonString)

Here, jsonString is the JSON string you want to convert into a JavaScript object.

Example

Parse a JSON string into a JavaScript object.

let studentJSON = '{"name": "Alice", "major": "Computer Science", "age": 20}';

// parse the JSON string into a JavaScript object
let student = JSON.parse(studentJSON);

// using the student object
console.log(student.name);
console.log(student.major);
console.log(student.age);

Once the received JSON string from the server (or stored in a variable) is converted into a JavaScript object, you can use it in your program.


Reading and writing JSON files in Node.js

Node.js is an environment to run JavaScript outside the browser. It is used to build server-side applications.

It provides a built-in module called fs (file system) to work with files. We are using this module to read and write any file.

Let's see how to read and write JSON files in Node.js.


1. Reading JSON file

To read a JSON file in Node.js, you can use the fs.readFile() method. This method takes two arguments: the file path and a callback function. The callback function is called with two arguments: an error object (if an error occurred) and the file's contents.

Here is an example to read a JSON file in Node.js.

Example

Read a JSON file in Node.js.

const fs = require('fs');

fs.readFile('file.json', (err, data) => {
  if (err) throw err;
  const obj = JSON.parse(data);
  console.log(obj);
});

In the above example, we first imported the fs module. Then use the fs.readFile() method to read the contents of the file.json file. If an error occurs, it is thrown. Otherwise, the contents of the file are parsed into a JavaScript object and printed to the console.


2. Writing JSON file

To write a JSON file in Node.js, you can use the fs.writeFile() method. This method takes three arguments:

  1. The file path
  2. The data to write
  3. A callback function

The callback function is called with one argument: an error object (if an error occurred).

Example

Write a JSON file in Node.js.

const fs = require('fs');

const obj = {
  name: 'Alice',
  major: 'Computer Science',
  age: 20
};
const jsonString = JSON.stringify(obj);

fs.writeFile('file.json', jsonString, (err) => {
  if (err) throw err;
  console.log('The file has been saved!');
});

In the above example, we first imported the fs module. Then use the fs.writeFile() method to write the contents of the obj object to the file.json file. If an error occurs, then the file is not written. Otherwise, the contents of the file are written to the file and a success message is printed to the console.


Summary

JSON works well with JavaScript. You can use it with ajax to send and receive data from the server. And also can modify the webpage on demand without reloading the page.

With this, all the limit is your imagination of what you can do with JSON.

Happy Learning!🙂