Tutorial

JSON.parse() and JSON.stringify()

JavaScript

While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

The JSON object, available in all modern browsers, has two useful methods to deal with JSON-formatted content: parse and stringify. JSON.parse() takes a JSON string and transforms it into a JavaScript object. JSON.stringify() takes a JavaScript object and transforms it into a JSON string.

Here’s an example:

const myObj = {
  name: 'Skip',
  age: 2,
  favoriteFood: 'Steak'
};

const myObjStr = JSON.stringify(myObj);

console.log(myObjStr);
// "{"name":"Skip","age":2,"favoriteFood":"Steak"}"

console.log(JSON.parse(myObjStr));
// Object {name:"Skip",age:2,favoriteFood:"Steak"}

And although the methods are usually used on objects, they can also be used on arrays:

const myArr = ['bacon', 'letuce', 'tomatoes'];

const myArrStr = JSON.stringify(myArr);

console.log(myArrStr);
// "["bacon","letuce","tomatoes"]"

console.log(JSON.parse(myArrStr));
// ["bacon","letuce","tomatoes"]

JSON.parse()

JSON.parse() can take a function as a second argument that can transform the object values before they are returned. Here the object’s values are uppercased in the returned object of the parse method:

const user = {
  name: 'John',
  email: 'john@awesome.com',
  plan: 'Pro'
};

const userStr = JSON.stringify(user);

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

Trailing commas are not valid in JSON, so JSON.parse() throws if the string passed to it has trailing commas.

JSON.stringify()

JSON.stringify() can take two additional arguments, the first one being a replacer function and the second a String or Number value to use as a space in the returned string.

The replacer function can be used to filter out values, as any value returned as undefined will be out of the returned string:

const user = {
  id: 229,
  name: 'John',
  email: 'john@awesome.com'
};

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

const userStr = JSON.stringify(user, replacer);
// "{"id":229,"name":"John"}"

And an example with a space argument passed-in:

const user = {
  name: 'John',
  email: 'john@awesome.com',
  plan: 'Pro'
};

const userStr = JSON.stringify(user, null, '...');
// "{
// ..."name": "John",
// ..."email": "john@awesome.com",
// ..."plan": "Pro"
// }"

If you’d like to learn more about JavaScript, take a look at our How To Code in JavaScript series, or check out our JavaScript topic page for exercises and programming projects.

0 Comments

Creative Commons License