DEV Community

Lourdes Suello
Lourdes Suello

Posted on • Updated on

Everything you know about JSON.parse() and JSON.stringify()

JSON.stringify()

Transforms a Javascript object to a JSON string.
A common use of JSON is to exchange data to/from a web server.
When sending data to a web server, the data has to be a string.
Convert a JavaScript object into a string with JSON.stringify().

Example:
Imagine we have this object in JavaScript:

const student = {
    name: "Alex",
    age: 20,
    email: "alex@gmail.com"
};

const studentStr = JSON.stringify(student);
console.log(studentStr);

{ "name":"Alex", "age":20, "email":"alex@gmail.com"}
Stringify a JavaScript Array

It is also possible to stringify JavaScript arrays.

Example:
Imagine we have this object in JavaScript:

const arrName = [ "John", "Peter", "Sally", "Jane" ];

const jsonName = JSON.stringify(arrName);
console.log(jsonName);

["John","Peter","Sally","Jane"]

JSON.parse()

Takes a JSON string and transform it into a Javascript Object.

Example:
Imagine we received this text from a web server.
We will take the studentStr sample above.

const jsObject = JSON.stringify(studentStr);
console.log(jsObject);

Object { age: 20, email: "alex@gmail.com", name: "Alex" }

Top comments (0)