loading...

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

attacomsian profile image Atta Updated on ・4 min read

JavaScript Revisited (15 Part Series)

1) How to show desktop notifications using JavaScript 2) Accepting Payments using JavaScript Payment Request API 3 ... 13 3) Understanding JSON.parse() and JSON.stringify() 4) Sets in JavaScript 5) Maps in JavaScript 6) Objects, Prototypes and Classes in JavaScript 7) Introduction to JavaScript Fetch API 8) Introduction to Service Workers in JavaScript 9) Getting DOM Elements using JavaScript 10) Introduction to JavaScript Arrow Functions 11) Introduction to JavaScript Regular Expressions 12) Introduction to XMLHttpRequest (XHR) 13) Object.entries() and Object.values() Methods in JavaScript 14) Using JavaScript Fetch API to Get and Post Data 15) Introduction to JavaScript URL Object

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"}

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));
// ["🐢", "πŸ¦‰", "πŸ’€", "πŸ¦†", "πŸ•"]

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);

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"]}'

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}'

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"
// }"

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

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

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

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.

JavaScript Revisited (15 Part Series)

1) How to show desktop notifications using JavaScript 2) Accepting Payments using JavaScript Payment Request API 3 ... 13 3) Understanding JSON.parse() and JSON.stringify() 4) Sets in JavaScript 5) Maps in JavaScript 6) Objects, Prototypes and Classes in JavaScript 7) Introduction to JavaScript Fetch API 8) Introduction to Service Workers in JavaScript 9) Getting DOM Elements using JavaScript 10) Introduction to JavaScript Arrow Functions 11) Introduction to JavaScript Regular Expressions 12) Introduction to XMLHttpRequest (XHR) 13) Object.entries() and Object.values() Methods in JavaScript 14) Using JavaScript Fetch API to Get and Post Data 15) Introduction to JavaScript URL Object

Posted on Jul 18 '19 by:

attacomsian profile

Atta

@attacomsian

I write about modern JavaScript, Node.js, Spring Boot, and all things web development. Subscribe to my newsletter: https://attacomsian.com/newsletter

Discussion

markdown guide