Open In App

What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development.

JSON.parse() Method

JSON.parse() converts a JSON string to a JavaScript object. It accepts a JSON string as input. It must be in string format when sending data to a web server locally. It’s useful for storing data in local storage as browsers store data in key-value pairs.

Syntax

JSON.parse( string, function )

Example: In this example, we define a constant myInfo containing JSON-like data. It’s parsed into an object Obj. The code then logs the values of Name and Age from Obj. The resulting output would be GFG and 22, respectively.

Javascript




const myInfo = `{
   "Name": "GFG",
   "Age":22,
   "Department" : "Computer Science and Engineering",
   "Year": "3rd"
}`
 
const Obj = JSON.parse(myInfo);
console.log(Obj.Name) 
console.log(Obj.Age)


Output

GFG
22

JSON.stringify() Method

JSON.stringify() converts JavaScript objects into JSON strings, accepting a single object argument. It contrasts JSON.parse(). With replacer parameters, logic on key-value pairs is feasible. Date formats aren’t allowed in JSON; thus, they should be included as strings.

Syntax

JSON.stringify(value, replacer, space);

Example: This example we converts the JavaScript object myInfo into a JSON string using JSON.stringify(). It then logs the resulting JSON string, which represents the object’s data.

Javascript




const myInfo = {
   Name: "GFG"
   Age:22,
   Department : "Computer Science and Engineering",
   Year: "3rd"
}
const Obj = JSON.stringify(myInfo);
console.log(Obj)


Output

{"Name":"GFG","Age":22,"Department":"Computer Science and Engineering","Year":"3rd"}

Difference Between JSON.stringify() Method & JSON.parse() Method

JSON.parse() JSON.stringify()
Converts JSON string to JavaScript object. Converts JavaScript object to JSON string.

The string must be wrapped in double quotes. example:  “String”.

No need to wrap the string in double quotes.

Accepts only one argument, the JSON string. Accepts only one argument, the JavaScript object.
Useful for parsing data received from servers. Useful for converting JavaScript objects for transmission.
Can handle JSON with nested objects and arrays. Preserves data types, including numbers, strings, arrays, and objects.
Can’t include functions or undefined values. Includes all enumerable properties, excluding functions and undefined values.
Handles dates as strings; must be converted. Allows optional replacer function to customize output or filter properties.


Last Updated : 06 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads