JSON Introduction

JSON: JavaScript Object Notation (JavaScript Object Notation).

JSON is a syntax for storing and exchanging data.

JSON is written in text using JavaScript Object Notation (JSON).

Data exchange

When data is exchanged between the browser and the server, these data must be in text format.

JSON is text, and we can convert any JavaScript object to JSON, then send the JSON to the server.

We can also convert any JSON received from the server to a JavaScript object.

In this way, we can handle data as JavaScript objects without the need for complex parsing and translation.

Send data

If your data is stored in a JavaScript object, you can convert the object to JSON and then send it to the server.

Example

var myObj = { name:"Bill Gates", age:62, city:"Seattle" };
var myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;

Try it yourself

You will learn more about it in the later chapters of this tutorial. JSON.stringify() Knowledge of functions.

Receive data

If you receive data in JSON format, you can convert it to a JavaScript object:

Example

var myJSON = '{ "name":"Bill Gates", "age":62, "city":"Seattle" }';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;

Try it yourself

You will learn more about it in the later chapters of this tutorial. JSON.parse() Knowledge of functions.

Storing data

When storing data, the data must be in a specific format, and regardless of where you choose to store it, text is always one of the valid formats.

JSON makes it possible for JavaScript objects to be stored as text.

Example

Store the data in local storage

//Store data:
myObj = { name:"Bill Gates", age:62, city:"Seattle" };
myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);
//Receive data:
text = localStorage.getItem("testJSON");
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name;

Try it yourself

What is JSON?

  • JSON stands for JavaScript Object Notation (JavaScript Object Notation)
  • JSON is a lightweight data interchange format
  • JSON is self-descriptive and easy to understand
  • JSON is independent of language*

*

JSON uses JavaScript syntax, but the JSON format is plain text.

Text can be read and used as data by any programming language.

JSON format was originally proposed by Douglas Crockford.

Why use JSON?

Because JSON format is just text, it can be easily transmitted between servers and browsers and used as a data format for any programming language.

JavaScript provides built-in functions to convert strings written in JSON format into native JavaScript objects:

JSON.parse()

Therefore, if you receive data in JSON format from a server, you can use it just like any other JavaScript object.