DEV Community

Cover image for JSON.stringify() & JSON.parse()
Katherine Hebbler
Katherine Hebbler

Posted on • Edited on

JSON.stringify() & JSON.parse()

JSON

JSON, or JavaScript Object Notation, is a text format for storing and transporting complex data. JavaScript includes simple methods for converting JSON text (stored as a String) to an Object or an Array, and JSON Objects and Arrays to JSON text.

This is useful when transferring data to be read by different systems, because sometimes only text can be stored or transmitted between them. For example, when sending data from a web app to a server via HTTP, it needs to be sent as a String. [.]

JSON.stringify() and JSON.parse() are built in Functions that can be used on JavaScript Objects and Arrays to convert them to and from JSON Strings.

JSON.stringify() converts a JavaScript Object or Array to a JSON String, which can be stored as text.

JSON.parse() converts a JSON String back into a JavaScript Object or Array.


Here, I have an Array called albums of album Objects, each containing two keys: "artist" and "title":

let albums = [
{
  "artist" : "Herbie Hancock",
  "title" : "Head Hunters",
},
{
  "artist" : "Beastie Boys",
  "title" : "Paul's Boutique"
},
  {
  "artist" : "The Cramps",
  "title" : "Bad Music for Bad People"
}
];

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

Logging albums gives the following output:

// [object Array] (3)
[// [object Object] 
{
  "artist": "Herbie Hancock",
  "title": "Head Hunters"
},// [object Object] 
{
  "artist": "Beastie Boys",
  "title": "Paul's Boutique"
},// [object Object] 
{
  "artist": "The Cramps",
  "title": "Bad Music for Bad People"
}]
Enter fullscreen mode Exit fullscreen mode

When calling console.log(albums);, the console sees that albums is an Array and shows [object Array] for the entire Array and [object Object] for each item inside of it. This shorthand is used by default.


JSON.stringify()

JSON.stringify() takes a JavaScript Array or Object and converts it into a JSON String (also called serialization).

Here, I'm converting the albums Array to a JSON String by invoking the JSON.stringify() method on albums, and assigning it to the variable jsonAlbumsString:

let jsonAlbumsString = JSON.stringify(albums);

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

Logging jsonAlbumsString gives the following output:

"[{"artist": "Herbie Hancock", "title": "Head Hunters"}, {"artist": 
"Beastie Boys", "title": "Paul's Boutique"}, {"artist": "The Cramps", 
"title": "Bad Music for Bad People"}]";
Enter fullscreen mode Exit fullscreen mode

This returns a JSON String representing an Array of three Objects, each with two properties.

⭐JSON has specific formatting, so Strings are wrapped in double quotes(""), and Object keys are also wrapped in double quotes("").


JSON.stringify() Parameters

The JSON.stringify() Function accepts up to three parameters:

  1. Value: the Object or Array to convert to a JSON String (in this case, albums).

  2. Replacer(Optional): a Function that lets you modify each key-value pair.

    • Set to null if not needed.
  3. Space(Optional): the number of spaces to use for indentation (in this case, 4).

let formattedAlbumString = JSON.stringify(albums, null, 4);

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

Logging formattedAlbumString gives the following output:

"[
    {
        'artist': 'Herbie Hancock',
        'title': 'Head Hunters'
    },
    {
        'artist': 'Beastie Boys',
        'title': 'Paul's Boutique'
    },
    {
        'artist': 'The Cramps',
        'title': 'Bad Music for Bad People'
    }
]"
Enter fullscreen mode Exit fullscreen mode

Here, each Object is now formatted with indentation, making it easier to debug and improving readability.

Albums1


Next, I've created a String, albumsString, representing three album Objects, each containing two keys: "artist" and "title":

(I've wrapped it in single quotes for readability.)

let albumsString = '[{"artist": "Bad Brains", "title": "Bad Brains"}, 
{"artist": "A Tribe Called Quest", "title": "The Low End Theory"}, {"artist": 
"Nina Simone", "title": "Wild is the Wind"}]'

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

Logging albumsString gives the following output:

"[{'artist': 'Bad Brains', 'title': 'Bad Brains'}, {'artist': 'A Tribe 
Called Quest', 'title': 'The Low End Theory'}, {'artist': 'Nina Simone', 
'title': 'Wild is the Wind'}]"
Enter fullscreen mode Exit fullscreen mode

Logging albumsString.length gives the following output:

console.log(albumsString.length); // length of String
172
Enter fullscreen mode Exit fullscreen mode

The length is 172 because albumsString is a single string, even though it looks like an Array of Objects.


JSON.parse()

JSON.parse() takes a JSON String and converts it into a JavaScript Object or Array (also called deserialization).

Here, I'm converting albumsString to an Array of Objects by invoking the JSON.parse() method on it, and assigning it to the variable parsedAlbumsArray:

let parsedAlbumsArray = JSON.parse(albumsString);

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

Logging parsedAlbumsArray gives the following output:

// [object Array] (3)
[// [object Object] 
{
  "artist": "Bad Brains",
  "title": "Bad Brains"
},// [object Object] 
{
  "artist": "A Tribe Called Quest",
  "title": "The Low End Theory"
},// [object Object] 
{
  "artist": "Nina Simone",
  "title": "Wild is the Wind"
}]
Enter fullscreen mode Exit fullscreen mode

Logging parsedAlbumsArray.length gives the following output:

console.log(parsedAlbumsArray.length); // length of Array
3
Enter fullscreen mode Exit fullscreen mode

Now, parsedAlbumsArray.length will be 3 because it is an Array with three elements.


JSON.parse() Parameters

The JSON.parse() Function accepts up to two parameters:

  1. Text: the string to parse as JSON (in this case, albumsString).

  2. Reviver: a Function that takes two parameters:

    1. key: the key associated with the value
    2. value: the value being parsed
  • The reviver Function is invoked recursively for each key-value pair.

  • "This reviver Function can be thought of as a filter Function." [.]

Here, I'm using JSON.parse() with a reviver Function to parse albumsString and filter its Objects so that I get only the albums by the artist "Nina Simone":

// initializing storage array
let ninaSimoneAlbums = [];
// parsing albumsString
  // using reviver to filter key-value pairs
JSON.parse(albumsString, (key, value) => {
  // if "artist" === "Nina Simone"
  if (key === "artist" && value === "Nina Simone") {
    // adding value to ninaSimoneAlbums
    ninaSimoneAlbums.push({ artist: value });
  }
  // returning value 
  return value;
});

console.log(ninaSimoneAlbums);
Enter fullscreen mode Exit fullscreen mode
  • The reviver Function checks if the key is "artist" and the value is "Nina Simone".
  • If both conditions are true, it adds the Object { artist: value } to the ninaSimoneAlbums Array.

Logging ninaSimoneAlbums gives the following output:

// [object Array] (1)
[// [object Object] 
{
  "artist": "Nina Simone",
  "title": "Wild is the Wind"
}]
Enter fullscreen mode Exit fullscreen mode

And if I want, I can convert ninaSimoneAlbums and parsedAlbumsArray back into JSON Strings using JSON.stringify() again.

console.log(JSON.stringify(ninaSimoneAlbums));
console.log(JSON.stringify(parsedAlbumsArray, null, 5));
Enter fullscreen mode Exit fullscreen mode

Logging this code gives the following output:

"[{'artist':'Nina Simone'}]"
"[
     {
          'artist': 'Bad Brains',
          'title': 'Bad Brains'
     },
     {
          'artist': 'A Tribe Called Quest',
          'title': 'The Low End Theory'
     },
     {
          'artist': 'Nina Simone',
          'title': 'Wild is the Wind'
     }
]"
Enter fullscreen mode Exit fullscreen mode

Albums2


JSON.stringify() and JSON.parse() are essential methods for working with JSON data. They allow you to convert complex JavaScript Objects and Arrays into JSON Strings and back again, making it easier to store and transfer.

  • JSON.stringify() converts JavaScript Objects an Arrays into JSON Strings.
  • JSON.parse() converts JSON Strings back into JavaScript Objects or Arrays.

These Functions allow for easy data exchange between systems.


Sources:

Top comments (0)