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
- Javascript Objects Cheatsheet
- How to fix 'Uncaught SyntaxError: Cannot use import statement outside a module'
- How to remove a specific item from an array
- Javascript Promise.all() - Everything you need to know
- How does the Javascript logical AND (&&) operator work?
- Inserting an Item into an Array at a Specific Index in Javascript
- How does the Javascript logical OR (||) operator work?
- Javascript Dates and How they Work
- How Promises and Await work in Javascript
- How to get the current URL with Javascript