DEV Community

Cover image for JSON Tutorial for Beginners in JavaScript and Node.js
Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer

Posted on • Originally published at learn.coderslang.com

JSON Tutorial for Beginners in JavaScript and Node.js

In this tutorial, you'll learn what JSON is and how to use it in JavaScript and Node.js.

Intro

One of the most popular formats for exchanging data between backend and frontend is JSON which stands for JavaScript Object Notation. It is very similar to what regular JavaScript objects look like, but it also has its own quirks. It reads - "jason" or "jay-sun", although you might hear some different pronunciations.

JSON does not impose any restrictions on the programming language that it can be used in. You can work in an organization where some of the backend services are written in Python, some in Java the frontend is in JS, and they all perfectly exchange JSON messages.

Storing data in JSON format

To begin with, 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, an object that refers to itself.

(Almost) everything should be wrapped in quotes

Unlike JavaScript, you should only use double quotes and wrap all object properties in them. You cannot use single quotes or backticks.

In JS, we had an object like this

{
  name: 'Jack',
  isMarried: false,
  age: 25,
}
Enter fullscreen mode Exit fullscreen mode

And in JSON it will become

{
  "name": "Jack",
  "isMarried": false,
  "age": 25
}
Enter fullscreen mode Exit fullscreen mode

Note that in JavaScript objects the presence of a comma after age: 25, is acceptable, but in JSON it is not.

All field names are wrapped in double-quotes, but not all primitive values are. Numbers and booleans are stored without quotes.

Objects are stored in curly braces

Curly braces are used to store objects, just like in JS.

Note that if the server responds in JSON format, then it is expected to respond with an object. You can't just list the fields. They all need to be wrapped in curly braces to become a JSON object.

Arrays are stored in square brackets

Everything is exactly like in JS, we wrap the name of the array in double-quotes, and the array itself is indicated in square brackets.

{
  "pets": ["Rex", "Sandy"]
}
Enter fullscreen mode Exit fullscreen mode

Note 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 pairs to an object. If you need to store multiple values without keys, then you need an array.

Convert JavaScript objects to JSON and back

To convert a regular JS object into a JSON string, you need the JSON.stringify(obj) function. It is available without installing additional 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}
Enter fullscreen mode Exit fullscreen mode

To convert from JSON to a regular object, we need the JSON.parse(s) function. We give a string in JSON format as input and get back 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}
Enter fullscreen mode Exit fullscreen mode

Express.js and JSON

If you're new to Express, I suggest starting with these articles:

Since we know that the JSON object is a string, we can very easily modify the server and send some object instead of Hello, Express.js.

Let's imagine we need to pass an object to the frontend

{
  name: 'Hero',
  isLearning: true,
  level: 'apprentice',
}
Enter fullscreen mode Exit fullscreen mode

We will do this in several ways. In all cases, the frontend will receive the same thing, which you can verify with a request in the browser.

  • Normal string:
server.get('/', (req, res) => {
  return res.send('{"name": "Hero", "isLearning": true, "level": "apprentice"}');
})
Enter fullscreen mode Exit fullscreen mode
  • Object transformed with JSON.stringify:
server.get('/', (req, res) => {
  const user = { name: 'Hero', isLearning: true, level: 'apprentice' };
  return res.send(JSON.stringify(user));
})
Enter fullscreen mode Exit fullscreen mode
  • Object transformed with res.json:
server.get('/', (req, res) => {
  const user = { name: 'Hero', isLearning: true, level: 'apprentice' };
  return res.json(user);
})
Enter fullscreen mode Exit fullscreen mode

I will repeat it. In all cases, the result is the same. We send a response with status 200 and the string {"name": "Hero", "isLearning": true,"level": "apprentice"}, which the recipient can use as they like.

To be honest, there’s a slight difference between res.send and res.json. There’s a special header Content-Type that’s set to text/html if you use res.send, and application/json if you choose res.json.

Use res.json if you have an object that you want to send in JSON format.

The third example is the most convenient one since we don't do any unnecessary actions. We pass the object to res.json and the conversion to JSON string happens internally. An additional (explicit) call to JSON.stringify, as in example 2, is not needed in this case.

Learn Full-Stack JavaScript

Top comments (1)

Collapse
 
andrewbaisden profile image
Andrew Baisden

Good read thanks for sharing your thoughts.