Complete JSON Tutorial


In this guide, you are going to learn everything about JSON, including its syntax, structure, and how to use it in programming languages.

    Table of Contents

  1. Introduction to JSON
    1. Use of JSON
    2. History of JSON
    3. Comparison to other data formats (XML, CSV, etc.)
  2. JSON syntax
  3. JSON data example
  4. Comments in JSON
  5. Working with JSON
    1. Working with JSON in JavaScript
  6. Advantages of JSON
  7. JSON vs XML
  8. Conclusion

Introduction to JSON

JSON stands for JavaScript Object Notation. It is a lightweight data-interchange format that is easy for humans to read and write.

It can be easily parsed and generated by machines. It is a language-independent data format.

JSON Tutorial

JSON was derived from JavaScript, but many modern programming languages include code to generate and parse JSON-format data.

JSON filenames use the extension .json.

{
  "name": "John Smith",
  "age": 30,
  "country": "United States"
}

The above JSON object has three keys ("name", "age", and "country") and three corresponding values ("John Smith", 30, and "United States").


Use of JSON

JSON is a common data format that is used in many different contexts. It includes:


History of JSON

JSON was first introduced in by Douglas Crockford as a way to encode data in a more human-readable and machine-readable format than XML, which was the dominant data interchange format at the time.

JSON quickly gained popularity due to its simplicity and flexibility, and it is now widely used in various contexts, including web development, mobile development, and data storage and exchange.


Comparison to other data formats (XML, CSV, etc.)

Apart from JSON, there are many other data formats that are used to store and exchange data. Some of the most popular ones are:

Here are a few key differences between these formats:

Format Human-readable Machine-readable
JSON ⭐⭐⭐⭐ Yes
XML ⭐⭐⭐ Yes
CSV ⭐⭐⭐ Yes
YAML ⭐⭐⭐⭐⭐ Yes
INI ⭐⭐⭐⭐ Yes

JSON is more lightweight and easier to work with than XML, and it is often preferred over CSV when working with APIs and when storing data in databases. However, each data format has its own strengths and weaknesses, and the right choice will depend on the specific needs of your application.


JSON syntax

A JSON object is a collection of key-value pairs, where the keys are strings and the values can be any valid JSON data type (such as strings, numbers, booleans, null, arrays, or other objects).

Rules for JSON syntax:

  • JSON data is written as name/value pairs.
  • Names are strings, and values are a valid JSON data type (string, number, object, array, boolean or null).
  • Objects are written in curly braces ({ }).
  • Always use double quotes (") around strings.
  • Names and values are separated by a colon (:).
  • Each name/value pair is separated by a comma (,).
  • Square brackets ([ ]) hold arrays.

Here is an example of a JSON object:

{
  "name": "John Smith",
  "age": 30,
  "isEmployed": true,
  "languages": ["English", "Spanish", "French"],
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "state": "NY"
  }
}

Please note that the keys must be enclosed in double quotes ", and the values can be any valid JSON data type. Numbers, booleans, and null do not need to be enclosed in double quotes.

Here is a breakdown of the above JSON object:

Key Value
name "John Smith"
age 30
isEmployed true
languages ["English", "Spanish", "French"]
address { "street": "123 Main St", "city": "New York", "state": "NY"}

JSON objects can also be nested within each other. For example, the address object is nested within the main object.

Note: A JSON file is saved with the .json extension.


JSON data example

Looking at the example will help you understand the syntax better.

Here are few examples of JSON data. For detailed look at various different JSON data, please visit JSON example.

Example 1: Simple JSON object

{
  "id": 1,
  "model": "BMW",
  "price": 100000
}

Example 2: JSON object with array

{
  "id": 1,
  "model": "BMW",
  "price": 100000,
  "colors": ["red", "blue", "green"]
}

Example 3: JSON object with nested object

{
  "id": 1,
  "model": "BMW",
  "price": 100000,
  "owner": {
    "name": "ABC",
    "mobile": "1234567890"
  }
}

Comments in JSON

JSON does not support comments. It is data-only.

If anyhow you want to add comments then it also must be data but you can mark a flag to ignore it.

Here is one of the ways to add comments in JSON:

{
  "name": "John Smith",
  "age": 30,
  "isEmployed": true,
  "_comment": "This is a comment"
}

Here, the _comment key is a flag to ignore the value and its value is a comment.


Working with JSON

The complete name of JSON (JavaScript Object Notation) may confuse you in thinking that it is a part of JavaScript but it is not. It is a data format that is completely language independent.

So you can work in any programming language that supports JSON to work with it. Like C++, Java, Python, PHP, JavaScript, etc.

Here we will see how to work with JSON in JavaScript.


Working with JSON in JavaScript

To work with JSON in JavaScript, you need to know 2 things:


Converting a JSON string to a JavaScript object

Use the JSON.parse() method and pass the JSON string as an argument to it. It will convert the JSON string to a JavaScript object and return it.

Example

Storing JSON data as a string and then converting it to a JavaScript object.

var jsonString = '{"name":"John", "age":30, "city":"New York"}';
        
// parse the JSON string to a JavaScript object
var obj = JSON.parse(jsonString);

// now you can access the object properties
console.log(obj.name); // John
console.log(obj.age); // 30
console.log(obj.city); // New York
John
30
New York

In the above example we stored a JSON string in a variable and then converted it to a JavaScript object using JSON.parse() method to get the object properties.

In real life scenario, you will get the JSON data from a server and then you will convert it to a JavaScript object to work with it.


Converting a JavaScript object to a JSON string

Now let's see how to convert a JavaScript object to a JSON string:

To convert a JavaScript object to a JSON string, you can use JSON.stringify() method.

Example

Converting a JavaScript object to a JSON string.

var obj = {
  name: "John",
  age: 30,
  city: "New York"
};

// convert the JavaScript object to a JSON string
var jsonString = JSON.stringify(obj);
console.log(jsonString);
{"name":"John","age":30,"city":"New York"}

Once an object is stringified, you can send it to a server and store it in a database.


Advantages of JSON

There are many advantages of using JSON over other data formats like XML.


JSON vs XML

Both JSON and XML are data formats that are used to store and transmit data. But there are some differences between them.

Feature JSON XML
Data format Key-value pairs Markup language
Syntax Simple, easy to read and write Verbose, more complex
Parsing Easy to parse with most programming languages Can be more complex to parse, depending on the language
Language independence Language-independent text-based format Tied to the XML language
Readability Simple, easy to read and understand Verbose, more difficult to read and understand
Support Widely supported by many languages and technologies Supported by many languages and technologies, but not as widely as JSON

Check out the JSON vs XML chapter to learn more about the differences between them.


Conclusion

You have learned the basics of JSON and how to use it in javascript.

Whether you are working with web APIs, mobile apps, web applications, or any other type of project, JSON is a valuable tool that can help you exchange data efficiently and effectively.

Let's explore more about JSON in the next chapter.

Happy Learning!😊