DEV Community

Cover image for Working with JSON in JavaScript
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

Working with JSON in JavaScript

Originally posted here!

JSON (aka, JavaScript Object Notation) is a format of transferring data between services, e.g: transferring data between a server and a client. Nowadays JSON is also used to write configuration files for many applications. It is readily available to use in most of the programming languages.


Let's discuss 2 methods of JSON available in JavaScript:

  • JSON.parse
  • JSON.stringify

Both these methods are available in the browser (window object) as well as in Nodejs (global object).

JSON.parse() method

JSON.parse is used to convert JSON data into a JavaScript object.

Consider this JSON.

// JSON
const json = `{
  "name": "John Doe",
  "age": 23
}`;
Enter fullscreen mode Exit fullscreen mode

Let's convert this JSON into a JavaScript object using the JSON.parse method.

// JSON
const json = `{
  "name": "John Doe",
  "age": 23
}`;

// Convert JSON to JavaScript object
const obj = JSON.parse(json);

/*

Result:
-------

{
    age: 23,
    name: "John Doe"
}

*/
Enter fullscreen mode Exit fullscreen mode
  • The method accepts a valid JSON string.

Yay! 🎊

JSON.stringify() method

JSON.stringify is used to convert a JavaScript object into JSON format.

// JavasScript Object
const obj = {
  name: "John Doe",
  age: 23,
};
Enter fullscreen mode Exit fullscreen mode

Let's convert this object into the JSON format.

// JavasScript Object
const obj = {
  name: "John Doe",
  age: 23,
};

// Convert JavaScript object into JSON
const json = JSON.stringify(obj);

/*

Result:
------

{
    "name":"John Doe",
    "age":23
}

*/
Enter fullscreen mode Exit fullscreen mode
  • The method accepts a valid JavaScript object.

Feel free to share if you found this useful 😃.


Top comments (2)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.