JSON.stringify() & JSON.parse() in JavaScript

The JSON object has two very useful methods to handle JSON-formatted content: parse and stringify.
You can transform a JavaScript object into a JavaScript string using JSON.stringify().
You can transform a JavaScript string into a JavaScript object using JSON.parse().

JSON.stringify():

Example:

const employee = {
name : "John Doe",
email : "johndoe@gmail.com",
age: 28
};

const employeeStr = JSON.stringify(employee);
console.log("employee object after stringified: ", employeeStr);

Output:

employee object after stringified: {“name”:”John Doe”,”email”:”johndoe@gmail.com”,”age”:28}

Most of the times JSON.parse() & JSON.stringify() are used on objects but they can be used on arrays also.

Example:

const employees = ['John', 'Jane', 'Leo']

const employeesStr = JSON.stringify(employees);
console.log("employee array after stringified: ", employeesStr);

Output:

employee array after stringified: [“John”,”Jane”,”Leo”]

JSON.parse():

Example:

const student = '{ "name":"Jane", "age":25, "city":"Florida"}'
const studentObj = JSON.parse(student);
console.log("student object after parsed: ", studentObj);

Output:

student object after parsed: {name: “Jane”, age: 25, city: “Florida”}

Using JSON.parse() on array:

const studentArr = JSON.parse('["John", "Jane", "Leo"]');
console.log("student array after parsed: ", studentArr);

Output:

student array after parsed: [“John”, “Jane”, “Leo”]

Arguments for JSON.stringify():

JSON.stringify() can take two arguments replacer function and Number or String value to use as space in the returned string.

Example with replacer function:

const employee = {
  name : "John Doe",
  email : "johndoe@gmail.com",
  age: 28
};

function replacer(key, value) {
  console.log(typeof value);
  if (key === 'age') {
    return undefined;
  }
  return value;
}

const employeeStr = JSON.stringify(employee, replacer);
console.log(employeeStr);

Output:

employee Object after: {“name”:”John Doe”,”email”:”johndoe@gmail.com”}

Example with space argument:

const employee = {
  name : "John Doe",
  email : "johndoe@gmail.com",
  age: 28
};

const employeeStr = JSON.stringify(employee, null, '***');
console.log("employee Obeject after:", employeeStr);

Output:

employee Obeject after: {
***”name”: “John Doe”,
***”email”: “johndoe@gmail.com”,
***”age”: 28
}

Arguments for JSON.parse():

You can pass second argument to JSON.parse() for reviver function which transforms object values before they are returned.
In the following example, all object values are transformed and then returned as lowercased.

Example:

const student = '{ "name":"Jane", "age":25, "city":"Florida"}';

JSON.parse(student, (key, value) => {
  if (typeof value === 'string') {
    return value.toLowerCase();
  }
  return value;
});

Output:

{name: “jane”, age: 25, city: “florida”}

Leave a Reply