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
- Instagram Style Video Preload Static Effect
- Removing the last element of an array in Javascript
- How to Make Payments with the Javascript Payments API
- Javascript Dates and How they Work
- Web Workers Tutorial: Learn how Javascript Web Workers Work
- How fetch works in Javascript
- How does Optional Chaining work in Javascript?
- Art Generator with Javascript and WebGL
- Javascript Operators and Expressions
- Making your own Email Subscription Service with Node.JS