JSON — short for JavaScript Object Notation — is a popular format for storing and exchanging data. As the name suggestions, JSON is basically derived from the JavaScript but later embraced by other programming languages.

JSON file ends with .json extension but it is not compulsory to store the JSON data in a file. You can even define a JSON object or an array in JavaScript or HTML file.

In a nutshell, JSON is lightweight, human-readable, and needs very less formatting that makes it a very good alternative to XML.

Syntax and Data Types

JSON data is stored as key-value pairs similar to JavaScript object properties, separated by commas, curly braces, and square brackets. A key-value pair consists of a key also called name (in double quotes), followed by a colon (:), followed by value (in double quotes):

"name": "Atta"

Multiple key-value pairs are separated by a comma:

"name": "Atta",
"age": 30

JSON keys are strings, always on the left of the colon, and must be wrapped in double quotes. Within each object, keys need to be unique and can contain whitespaces, as in "author name": "John Doe".

It is not recommended to use whitespaces in keys. It will make it difficult to access the key during the programming. Instead, use underscore in keys, as in "author_name": "John Doe".

JSON values must be one of the following data types:

  • String
  • Number
  • Boolean (true or false)
  • Null
  • Object
  • Array

Unlike JavaScript, JSON values cannot be a function, a date or undefined.

JSON Strings

String values in JSON are a set of characters wrapped in double quotes:

{
    "firstName": "John",
    "lastName": "Doe"
}

JSON Numbers

A number value in JSON must be an integer or a floating point:

{
    "age": 45,
    "weight": 75.5
}

JSON Booleans

Boolean values are simple true or false in JSON:

{
    "admin": true
}

JSON Null

Null values in JSON are empty words:

{
    "middleName": null
}

JSON Objects

JSON objects are wrapped in curly braces. Inside the object, we can list any number of key-value pairs, separated by commas:

{
    "firstName": "John",
    "lastName": "Doe",
    "email": "john.doe@example.com",
    "age": 45,
    "weight": 67,
    "admin": true
}

JSON Arrays

JSON arrays are wrapped in square brackets. Inside an array, we can declare any number of objects, separated by commas:

[
    {
        "name": "Jason",
        "gender": "M",
        "age": 27
    },
    {
        "name": "Rosita",
        "gender": "F",
        "age": 23
    },
    {
        "name": "Leo",
        "gender": "M",
        "age": 19
    }
]

In the above JSON array, there are three objects. Each object is a record of a person (with name, gender and age).

Nesting Objects & Arrays

JSON can store nested objects and arrays as values assigned to keys. It is very helpful for storing different sets of data in one file:

{
    "name": "Jason Ray",
    "profession": "Software Engineer",
    "age": 31,
    "address": {
        "city": "New York",
        "postalCode": 64780,
        "Country": "USA"
    },
    "languages": ["Java", "Node.js", "JavaScript", "JSON"],
    "socialProfiles": [
        {
            "name": "Twitter",
            "link": "https://twitter.com"
        },
        {
            "name": "Facebook",
            "link": "https://www.facebook.com"
        }
    ]
}

Transforming JSON Data in JavaScript

The JSON format iis syntactically similar to the way we create JavaScript objects. Therefore, it is easier to convert JSON data into JavaScript native objects.

JavaScript built-in JSON object provides two important methods for encoding and decoding JSON data: parse() and stringify().

JSON.parse() takes a JSON string as input and converts it into JavaScript object:

// declare a JSON string
const me = `{ "name": "Atta", "age": 30, "twitter": "@attacomsian" }`;

// parse JSON string
const data = JSON.parse(me);

console.log(data.name); // Atta
console.log(data.age); // 30
console.log(data.twitter); // @attacomsian

JSON.stringify() does the opposite. It takes a JavaScript object as input and transforms it into a string that represents it in JSON:

const data = {
    name: 'Atta',
    age: '30',
    twitter: '@attacomsian'
};

// convert it to string
const me = JSON.stringify(data);

console.log(me);

// {"name":"Atta","age":"30","twitter":"@attacomsian"}

JSON vs XML

A few years back, XML (Extensible Markup Language) was a popular choice for storing and sharing data over the network. But that is not the case anymore.

JSON has emerged as a popular alternative to XML for the following reasons:

  1. Less verbose — XML uses much more words than required, that makes it time-consuming to read and write.
  2. Lightweight & faster — XML must be parsed by an XML parser, but JSON can be parsed using JavaScript built-in functions. Parsing large XML files is slow and requires a lot of memory.
  3. More data types — You cannot store arrays in XML which are extensively used in JSON format.

Let us see an example of an XML document and then the corresponding document written in JSON:

databases.xml

<databases>
	<database>
		<name>MySQL</name>
		<type>RDBMS</type>
	</database>
	<database>
		<name>MongoDB</name>
		<type>NoSQL</type>
	</database>
	<database>
		<name>Neo4j</name>
		<type>Graph DB</type>
	</database>
</databases>

databases.json

{
    "databases": [
        {
            "name": "MySQL",
            "type": "RDBMS"
        },
        {
            "name": "MongoDB",
            "type": "NoSQL"
        },
        {
            "name": "Neo4j",
            "type": "Graph DB"
        }
    ]
}

As you can see above, the XML structure is not intuitive, making it hard to represent in code. On the other hand, the JSON structure is much more compact and intuitive, making it easy to read and map directly to domain objects in any programming language.

JSON Resources

There are many useful resources available online for free to learn and work with JSON:

  • Introducing JSON — Learn the JSON language supported features.
  • JSONLint — A JSON validator that you can use it to verify if the JSON string is valid.
  • JSON.dev — A little tool for viewing, parsing, validating, minifying, and formatting JSON.
  • JSON Schema — Annotate and validate JSON documents according to your own specific format.

Further Reading

A few more articles related to JSON that you might be interested in:

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Buy me a coffee (cost $3)

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.