JavaScript - JSON

Tanwa Sripan - Jun 4 '22 - - Dev Community

Hey all 👋 I have been learning a lot about backend development and creating APIs with NodeJS, Express and MongoDB. So, I wanted to write a little bit about JavaScript Object Notation (JSON) and share what I know about them.

Table of content

  1. Introduction
  2. Methods and Examples
  3. Summary

Introduction

Although the name is JavaScript Object Notation, it is actually widely used in many programming languages not just JS. JSON is a way of formatting data and representing them as plain text and it is often written as key-value pairs similar to the JS Objects. It is commonly used for API as it allows for data to be transferred over network requests and it is often used in configuration files of projects (e.g package.json 👀). JSON is very easy to read/write and using them is also easy.

JSON represents data in plain text and it supports many data types such as String, Booleans, Numbers, Arrays, Objects and null. However, it cannot represent Functions, Symbols, etc.

JSON is language independent.

Methods and Examples

The two main methods that you can use when dealing with JSON are JSON.stringify() and JSON.parse() in JavaScript (other languages will have their own versions of this).

JSON.stringify() - When you would like to convert JS Objects into a JSON string in preparation to send data over the web for example, you can use this method. If an object to be stringify has its own toJSON method then JSON.stringify will use that during the process, an example of this is the Date object.

Converting objects to JSON string is sometimes known as serializing or json-enconding.

Syntax and Example:

The full syntax is JSON.stringify(value, replacer, space), where the replacer allow you to modify how you would like the value to be stringify while the "space" option allow you to define the white spaces for better visual representation of the JSON string.

const data = {
  name: "Michael Scott", 
  dob: "15/03/1964", 
  position: "regional manager",
  employees: ["Jim", "Pam", "Dwight", "Angela", "Kevin", "Stanley"],
  lover: {name: "Holly", dob: "03/03/1972"},
  date_added: new Date()
}

const json_data = JSON.stringify(data);

console.log(typeof json_data); // "string"
console.log(json_data); 
// '{"name":"Michael Scott","dob":"15/03/1964","position":"regional manager","employees":["Jim","Pam","Dwight","Angela","Kevin","Stanley"],"lover":{"name":"Holly","dob":"03/03/1972"},"date_added":"2022-06-04T12:33:30.479Z"}'

Enter fullscreen mode Exit fullscreen mode

JSON.parse() - This method allow you to convert JSON string to JS object. You may use this if you wanted to parse some data you received from an API request for example.

Syntax and Example:

The full syntax is JSON.parse(text, reviver), where the reviver allow you transform the value before returning it.

const json_encoded = '{"name": "Jim", "position": "salesperson", "likes": ["ham", "cheese" , "Pam"] }'

const data = JSON.parse(json_encoded);

console.log(typeof data); // "object"
console.log(data.likes[1]) // "cheese"

Enter fullscreen mode Exit fullscreen mode

JSON.parse will not automatically parse into the Date object, so you can use the reviver option to convert the date string into a Date object, for example:


let json_date = '{"date":"2022-06-04T12:33:30.479Z"}'

function reviver(key, value) {
  if (key === 'date') {
    return new Date(value);
  }
  return value;
}

const data = JSON.parse(json_date, reviver);
console.log(data.date.getFullYear()) // 2022

Enter fullscreen mode Exit fullscreen mode

Here, I have defined the reviver function but you could use anonymous function if you wanted to, it takes the key and value pair of the JSON string and if the key matches "date" then we would return a Date object of the value rather than the automatic JSON.parse value.

Summary

JSON is a data representation format that is independent of programming languages. You can use JSON.stringify() and JSON.parse() in JavaScript to convert to (serialize) and from (deserialize) JSON string/text. It can support Primitive values, null, arrays and objects. It is lightweight and easy to use, and you can add options to deal with how you convert to and from JSON.

That is all for today, if you have anything to add please let me know either in the comment below or via Twitter.

Det. Conan Anime

. . . . . . . . . . . . . . . . . . . . . . . . .