How to parse JSON object using JSON.stringify() in JavaScript?

By IncludeHelp Last updated : January 27, 2024

Problem statement

Given a JSON object, you have to parse the JSON object to a JSON string using the JSON string using the JSON.stringify().

Parsing JSON object using JSON.stringify()

To parse JSON object, you can use the JSON.stringify() method which converts JavaScript value (an object) to the string.

Syntax of JSON.stringify() Method

Below is the syntax of the JSON.stringify() method:

JSON.stringify(value);

Here, the value is the given object to be converted into the string.

JavaScript code to parse JSON object using JSON.stringify()

This code parses the given JSON object (obj) to the string.

// Creating an JSON object
var person = {
  Name: "Alvin Alexander",
  Email: "[email protected]",
  City: "New Delhi",
  Age: 21
};

// Printing object and its type before parsing
console.log("Before parsing...");
console.log("person: ", person);
console.log("Type of person: ", typeof person)

// Parsing JSON object
var result = JSON.stringify(person);

// Printing object and its type before parsing
console.log("After parsing...");
console.log("result: ", result);
console.log("Type of result: ", typeof result);

Output

The output of the above code is:

Before parsing...
person:  {
  Name: 'Alvin Alexander',
  Email: '[email protected]',
  City: 'New Delhi',
  Age: 21
}
Type of person:  object
After parsing...
result:  {"Name":"Alvin Alexander","Email":"[email protected]","City":"New Delhi","Age":21}
Type of result:  string
Note

Never miss to write JavaScript code inside the <script>...</script> tag.

Also Learn: Where to place JavaScript Code?

To understand the above example, you should have the basic knowledge of the following JavaScript topics:

All JavaScript Examples

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.