JSON.stringify() & JSON.parse()
Katherine Hebbler
Posted on November 14, 2024
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);
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"
}]
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);
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"}]";
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:
Value: the Object or Array to convert to a JSON String (in this case,
albums
).-
Replacer(Optional): a Function that lets you modify each key-value pair.
- Set to
null
if not needed.
- Set to
Space(Optional): the number of spaces to use for indentation (in this case,
4
).
let formattedAlbumString = JSON.stringify(albums, null, 4);
console.log(formattedAlbumString);
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'
}
]"
Here, each Object is now formatted with indentation, making it easier to debug and improving readability.
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);
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'}]"
Logging albumsString.length
gives the following output:
console.log(albumsString.length); // length of String
172
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);
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"
}]
Logging parsedAlbumsArray.length
gives the following output:
console.log(parsedAlbumsArray.length); // length of Array
3
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:
Text: the string to parse as JSON (in this case,
albumsString
).-
Reviver: a Function that takes two parameters:
-
key
: the key associated with the value -
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);
- 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 theninaSimoneAlbums
Array.
Logging ninaSimoneAlbums
gives the following output:
// [object Array] (1)
[// [object Object]
{
"artist": "Nina Simone",
"title": "Wild is the Wind"
}]
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));
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'
}
]"
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:
- w3schools - JSON
- mdn - Sending and Retrieving Form Data
- mdn - JSON.stringify()
- mdn - JSON.parse()
- mdn - Serialization
- mdn - Stringify: Parameters
- mdn - Stringify: Value
- mdn - Stringify: Replacer
- mdn - Stringify: Space
- mdn - Deserialization
- mdn - Parse: Parameters
- mdn - Parse: Text
- mdn - Parse: Value
- digitalocean - How To Use JSON.parse() and JSON.stringify()
- JSON.org
Posted on November 14, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.