DEV Community

Atta
Atta

Posted on • Updated on • Originally published at attacomsian.com

Understanding JSON.parse() and JSON.stringify()

This post was originally published on attacomsian.com/blog.


JSON (JavaScript Object Notation) is a lightweight, human-readable format for exchanging data. Originally derived from JavaScript, it is available for use with many programming languages including Java, Python, C#, PHP and Ruby.

For JavaScript asynchronous operations, it is a natural choice to use as a data format. The JSON object has two important methods for transforming and storing JSON data: parse() and stringify(). The JSON.parse() method takes a string as input and transforms it into an object. Similarly, JSON.stringify() takes a JSON object and converts it into a string.

Let's have an example:

const jsonObj = {
    id: 1,
    name: 'Hamburger',
    icon: '🍔',
    type: 'Food'
};

// convert JSON object to string
const jsonStr = JSON.stringify(jsonObj);

console.log(jsonStr);
// '{"id":1,"name":"Hamburger","icon":"🍔","type":"Food"}'

//convert string back to JSON object
console.log(JSON.parse(jsonStr));
// {id: 1, name: "Hamburger", icon: "🍔", type: "Food"}
Enter fullscreen mode Exit fullscreen mode

These methods are not just limited to JSON objects. You can also use them to transform JSON arrays to string and vice versa:

const jsonArr = ['🐶', '🦉', '💀', '🦆', '🍕'];

const jsonStr = JSON.stringify(jsonArr);

console.log(jsonStr);
// '["🐶","🦉","💀","🦆","🍕"]'

console.log(JSON.parse(jsonStr));
// ["🐶", "🦉", "💀", "🦆", "🍕"]
Enter fullscreen mode Exit fullscreen mode

JSON.stringify()

As name suggests, the JSON.stringify() function transforms a JavaScript object into a JSON string. While sending JSON data from a client to a server, it must be converted into a JSON string. JSON.stringify() can also take two more optional parameters:

  • replacer - either a function or an array to manipulate the result.
  • space - either a string or a number.

The replacer function is called for each property in the object and can be used to remove specific values from the returned JSON string:

const user = {
    id: 599,
    name: 'John Doe',
    email: 'john.doe@example.com',
    password: '123abc',
    age: 30,
    address: {
        city: 'New York',
        country: 'United States'
    },
    hobbies: ['Fishing', 'Golf', 'Table Tennis']
};

const str = JSON.stringify(user, (key, value) => {
    // filter-out password from final string
    if (key === 'password') {
        return undefined;
    }
    return value;
});

console.log(str);
Enter fullscreen mode Exit fullscreen mode

Here is the JSON string returned by the above code which does not include the password property:

'{"id":599,"name":"John Doe","email":"john.doe@example.com","age":30,"address":{"city":"New York","country":"United States"},"hobbies":["Fishing","Golf","Table Tennis"]}'
Enter fullscreen mode Exit fullscreen mode

If an array is passed as a replacer, only those properties of the object that exist in the array will be included in the resulting JSON string:

const str = JSON.stringify(user, ['name', 'email', 'age']);

console.log(str);
// '{"name":"John Doe","email":"john.doe@example.com","age":30}'
Enter fullscreen mode Exit fullscreen mode

Note: The replacer function cannot used to remove values from an array. If you return undefined or a function then null is used instead.

A space can be either a string of up to 10 characters or a number between 0 and 10. If a string is specified, it will be used as white space. On the other hand, the number indicates how many space characters to use as white space. Here is an example:

const dog = {
    name: 'Bablu',
    image: '🐶',
    age: '6 months'
};

const str = JSON.stringify(dog, null, '----');

console.log(str);

// "{
// ----"name": "Bablu",
// ----"image": "🐶",
// ----"age": "6 months"
// }"
Enter fullscreen mode Exit fullscreen mode

JSON.parse()

The JSON.parse() function does the opposite. It takes a JSON string as input and transforms it into a JavaScript object:

const str = '{"name":"Bablu","image":"🐶","age":"6 months"}';

const dog = JSON.parse(str);

console.log(dog.name); // Bablu
console.log(dog.image); // 🐶
console.log(dog.age); // 6 months
Enter fullscreen mode Exit fullscreen mode

An optional reviver function can also be passed to transform the object properties before they are returned:

const str = '{"id":99,"name":"Bablu","image":"🐶","age":"6 months"}';

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

console.log(dog.id); // 99
console.log(dog.name); // BABLU
console.log(dog.image); // 🐶
console.log(dog.age); // 6 MONTHS
Enter fullscreen mode Exit fullscreen mode

Trailing commas are not allowed in JSON. So JSON.parse() throws an exception if the string passed as argument has trailing commas:

JSON.parse('[1, 2, 3, 4, ]'); 
// Unexpected token ] in JSON at position 13
JSON.parse('{"name": "John Doe", "age": 29, }'); 
// Unexpected token } in JSON at position 32
Enter fullscreen mode Exit fullscreen mode

Summary

JSON is a lightweight format for sharing data between a client and a server. It has become a natural choice for making asynchronous requests in JavaScript and many other programming languages. For transforming and storing data, the JSON object provides two useful methods:

  • JSON.stringify() takes a JavaScript object as input and transforms it into a JSON string. It can take two optional parameters: replacer and space.
    • The replacer can be either a function or an array used to filter-out values from the resulting JSON string.
    • The space argument is either a number or a string. It is used to control spacing in the final string.
  • JSON.parse() does the opposite. It takes a JSON string and converts it back to a JavaScript object or value. An optional reviver function can be passed to perform a transformation on the object before it is returned.

✌️ I write about modern JavaScript, Node.js, Spring Boot, and all things web development. Subscribe to my newsletter to get web development tutorials & protips every week.


Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV.

Top comments (0)