JSON IN JAVASCRIPT

JSON and JavaScript 101

JSON stands for JavaScript Object Notation. It is one of the popular formats to store, transfer and structure data and in this post, I’ll explain the standard definition and usage of JSON in JavaScript.

JSON is not JavaScript

JSON is basically a text-based format to store data, it follows the JavaScript object syntax and can be used in any language. JSON is not a JavaScript object.

Key Properties of JSON

  • Text-based format
  • Lightweight in nature
  • Human readable format
  • Contains key/value pairs
  • Separated using commas
  • Enclosed in double quotes
  • JSON cannot contain functions
  • JSON is independent of language

JSON data types

  • String
  • Number
  • Array
  • Object
  • Boolean
  • Null

String

{ "name" : "Jhon" }

Number

Numbers in JSON are integers and need not be stored in quotes

{ "age" : 26 }

Array

[ 10, 20, 30, 40, 50 ]

Object

{
   "name":"Jhon",
   "age":26,
   "favouriteColors":[
      "Red",
      "Yellow"
   ]
}

Boolean

{ "isStudent" : true }

Null

Unknown values can be represented with null.

{ "name" : null }

ūüďĚNote: If a number exists inside quotes then after parsing it will become a string.

JSON, the cool kid on the Network block

API-friendly syntax, excellent compatibility with JavaScript has made JSON a popular format for sharing data over the internet. Often used for network requests between the client and server.

JavaScript functions for JSON

As JSON can contain strings, objects, and arrays this makes it convenient to convert it into a JavaScript object and vice versa. There are also two built-in functions for these operations.

  • JSON.parse() to convert JSON into a JavaScript object
  • JSON.stringify() to convert JavaScript objects to JSON

Convert JSON to JavaScript object

The JSON.parse() function to converts JSON data into a JavaScript object.

const jsonString = `{"color" : "red", "number": 99 }`;
const jsObject = JSON.parse(jsonString);
console.log(jsObject);

// Output
{
color:"red",
number:"99"
}

Convert JavaScript object to JSON

The JSON.stringify() function to converts JavaScript objects into JSON format.

const studentObject = {name: "Sam", class: 4 };
const jsonString = JSON.stringify(studentObject);
console.log(jsonString);

// Output
{"name":"Sam","class":4}

Accessing JSON

JSON data is essentially made up of key/value pairs so after converting it into a JavaScript object we can access it using the key by dot notation (.) or square brackets of [ ] the key.

const user = {
    name = "NEO",
    city = "Matrix"
}

console.log(user.name); // NEO
console.log(user["city"]); // Matrix

ūüďĚNote: Even a single missing comma can invalidate entire JSON data.
So, what are you planning to build with JSON?

Tags: