In this tutorial, you’ll learn what JSON is and how to use it in JavaScript and Node.js.
introduce
One of the most popular formats for exchanging data between the back end and front end is JSON, which is used to represent JavaScript objects. It looks very similar to a regular JavaScript object, but has its own unique features. It’s pronounced “Jason” or “Jay-sun,” so you might hear a few different pronunciations.
JSON has no restrictions on the programming language it uses. You can work in an organization where some back-end services are written in Python, some are Java, and some are JS, and they all perfectly exchange JSON messages.
Store data in JSON format
First, JSON is a string. This allows for very efficient data compression when needed. The disadvantage is that we cannot store circular data structures, for example, objects that reference themselves.
(Almost) everything should be enclosed in quotes
Unlike JavaScript, you should only use double quotes and wrap all object attributes in them. You cannot use single or backquotes.
In JS, we have an object that looks like this
{
name: 'Jack'.isMarried: false.age: 25,}Copy the code
In JSON, it becomes
{
"name": "Jack"."isMarried": false."age": 25
}
Copy the code
Note: In JavaScript objects, it is acceptable to have a comma age: 25 after a comma, but not in JSON.
All field names are enclosed in double quotes, but not all original values are enclosed in double quotes. Numbers and Booleans are stored without quotes.
Objects are stored in curly braces
As in JS, curly braces are used to store objects.
Note that if the server responds in JSON format, it is expected to respond as an object. You can’t just list these fields. They all need to be enclosed in braces to become JSON objects.
Arrays are stored in square brackets
Everything is exactly the same as in JS, we enclose the names of the arrays in double quotes, and the arrays themselves are represented in square brackets.
{
"pets": ["Rex"."Sandy"]}Copy the code
Notice again that there is no comma or semicolon at the end of the line.
All JSON object data is stored as “key”: “value” pairs
As in JS, you can only add key:value to objects for pairs. If you need to store multiple values without keys, you need an array.
Convert the JavaScript object to JSON and return it
To convert a regular JS object into a JSON string, you need this json.stringify (obj) function. It can be used without installing other modules. You pass it an object, obj, and get a JSON object as output.
const user = {
name: 'Jack'.isMarried: false.age: 25,}const userJSON = JSON.stringify(user);
console.log(userJSON); // {"name": "Jack", "isMarried": false, "age": 25}
Copy the code
To convert from JSON to a regular object, we need the json.parse (s) function. We take a JSON-formatted string as input and return a plain JS object.
const jsonString = '{"name": "Jack", "isMarried": false, "age": 25}';
const parsedUser = JSON.parse(jsonString);
console.log(parsedUser); // {name: 'Jack', isMarried: false, age: 25}
Copy the code
Express. Js and JSON
If you’re not familiar with Express, I’ll cover it in a future article:
- How do I create an Express server
- Fast middleware and external access
Since we know that the JSON object is a string, we can easily modify the server and send some objects instead of Hello, express.js.
Suppose we need to pass an object to the front end
{
name: 'Hero'.isLearning: true.level: 'apprentice',}Copy the code
We will do this in several ways. In all cases, the front end receives the same content, which you can verify with a request in the browser.
- Common string:
server.get('/'.(req, res) = > {
return res.send('{"name": "Hero", "isLearning": true, "level": "apprentice"}');
})
Copy the code
- Object converted to json.stringify:
server.get('/'.(req, res) = > {
const user = { name: 'Hero'.isLearning: true.level: 'apprentice' };
return res.send(JSON.stringify(user));
})
Copy the code
- Object converted to res.json:
server.get('/'.(req, res) = > {
const user = { name: 'Hero'.isLearning: true.level: 'apprentice' };
return res.json(user);
})
Copy the code
I’ll repeat it. In all cases, the result is the same. We send a response with status 200 and a string, {“name”: “Hero”, “isLearning”: true,”level”: “Apprentice “} the recipient can use the string as needed.
To be honest, there are subtle differences between res.send and res.json. If used, and selected, a special content-Type header is set. text/htmlres.sendapplication/jsonres.json
Res.json Use this property if you have objects that you want to send in JSON format.
The third example is the most convenient because we don’t do anything unnecessary. We pass the object to res.json and internally convert it to a JSON string. Json.stringify In this case, no additional (explicit) calls are required as in Example 2.
Finally, I would like to share a website for learning full stack JavaScript:
js.coderslang.com/
More vivid and interesting introduction learning
Thank you for reading to the end ❤️ here is your medal
And finally, don’t forget ❤ or 📑