How JSON works in Javascript
📣 Sponsor
JSON stands for Javascript Object Notation. It is a flexible way to store data, but ultimately it is a Javascript Object.
What does JSON look like?
JSON is a simple object structure. Sometimes, it is in separate files, with a .json ending, or sometimes it is in Javascript itself stored in a variable. APIs and NoSQL Databases often return data or store data as JSON.
Below is an example of a person described in JSON:
{
"firstName" : "John",
"lastName" : "Smith",
"age" : "99",
"address" : {
"streetAddress" : "123 Fake Street",
"city" : "FakeTown",
"zipCode" : "12345"
},
"someIds" : [ 123, 234, 345 ]
}
JSON is flexible, so the names you use are not set in stone. You can store any types of data as you normally would in Javascript (i.e. numbers, booleans, arrays, etc).
Working with JSON
JSON is often sent or received via APIs. As such, we have a few tools to manipulate JSON. The two biggest ones we have are JSON.parse and JSON.stringify. If we are sending JSON, we often stringify it, which will turn it into a string. Then, JSON-like strings can be turned back into a Javascript object using JSON.parse. Let's use our original JSON, and take a look at how these work:
let myJSON = {
"firstName" : "John",
"lastName" : "Smith",
"age" : "99",
"address" : {
"streetAddress" : "123 Fake Street",
"city" : "FakeTown",
"zipCode" : "12345"
},
"someIds" : [ 123, 234, 345 ]
}
let stringifyJSON = JSON.stringify(myJSON);
When we stringify our JSON, we end up with this, which is an escaped version of our original JSON in string form:
"{\"firstName\":\"John\",\"lastName\":\"Smith\",\"age\":\"99\",\"address\":{\"streetAddress\":\"123 Fake Street\",\"city\":\"FakeTown\",\"zipCode\":\"12345\"},\"someIds\":[123,234,345]}"
Using JSON.parse
will turn that string back into a Javascript object:
let stringJSON = "{\"firstName\":\"John\",\"lastName\":\"Smith\",\"age\":\"99\",\"address\":{\"streetAddress\":\"123 Fake Street\",\"city\":\"FakeTown\",\"zipCode\":\"12345\"},\"someIds\":[123,234,345]}";
let parsedJSON = JSON.parse(stringJSON); // This is now a javascript object!
More Tips and Tricks for Javascript
- Creating a NodeJS Push Notification System with Service Workers
- How does Optional Chaining work in Javascript?
- Inserting an Item into an Array at a Specific Index in Javascript
- Javascript Map, and How it is Different from forEach
- How Generator Functions work in Javascript
- Javascript Array Reduce Method
- Asynchronous Operations in Javascript
- Javascript Comments
- How to get the last element of an Array in Javascript
- Javascript: Check if an Array is a Subset of Another Array