Table of Contents
Introduction to JSON
JSON stands for JavaScript Object Notation and is a data format meant to store and transfer data. You've seen a format very similar to it any time you've logged JavaScript objects in your console.
You can think of JSON as a string-representation of the data inside a JavaScript object. As such, JSON supports the following values:
- string
- number
- object
- array
- boolean
- null
Here's an example of some JSON containing data about a random fictional person:
JSON{
"name": "Josh",
"weight": 175,
"age": 40,
"eyecolor": "brown",
"cars": [ "Chevy", "Toyota", "Honda" ],
"favoriteBook": {
"title": "When the Fire Nation Attacked",
"author": "Nickelodeon",
"released": "02-21-2005"
}
}
Javascript and JSON work really together thanks to the methods stringify and parse, provided by the JSON object.
These two methods convert a JavaScript object to JSON and back, so no matter which one you have, you can easily generate the other.
Stringify
You can use the stringify method to convert a JavaScript object to JSON.
JAVASCRIPTconst dog = {
"name": "Sophie",
"age": 3,
"weight": 20
}
const dogJSON = JSON.stringify(dog);
console.log(dogJSON);
HTML{"name":"Sophie","age":3,"weight":20}
Using stringify on a JavaScript object.
Stringify took the dog JavaScript object and converted it into a string. That string is now valid JSON and can be saved to a file or transferred over the network.
Parse
To get a JavaScript object from JSON, you must parse it, essentially the reverse of using stringify. Using the results we got above, let's parse that JSON and turn it into a JavaScript object:
JAVASCRIPTconst json = '{"name":"Sophie","age":3,"weight":20}';
const dog = JSON.parse(json);
console.log(dog);
Parsing JSON into a JavaScript object.
Now that dog is a normal JavaScript object, you can now use it as if it were created without JSON at all.
Resources
Getting Started with Solid
Managing PHP Dependencies with Composer
Getting Started with Express
Getting Started with Electron
How to deploy a .NET app using Docker
Best Visual Studio Code Extensions for 2022
How to build a Discord bot using TypeScript
How to deploy a MySQL Server using Docker
Learn how to use v-model with a custom Vue component
Getting Started with Handlebars.js
Getting Started with Vuex: Managing State in Vue
Using Axios to Pull Data from a REST API
