JSON – Introduction

JSON stands for: JavaScript Object Notation.

JSON is a syntax for storing and exchanging data.

JSON is text, written(in key value pair) with JavaScript object notation.

What is JSON?

  • JSON stands for JavaScript Object Notation
  • JSON is a lightweight data-interchange formatted string written in key value pair
  • JSON is “self-describing” and easy to understand
  • JSON is language independent

Why use JSON?

As the JSON format is lightweight text only, it can simply be sent to and from a server, and used as a data format by any programming language.

JavaScript has a built in or perdefined function to convert a string, written in JSON format, into native JavaScript objects:

JSON.parse()

So, if user receive the data from server, in JSON format, user can use it like any other JavaScript object.

Exchanging Data

While exchanging the data between a browser and server, the data can only be text.

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

By doing this way user can work with the data as JavaScript objects, without any problem in parsing and translations.

Sending Data

If user have data stored in a JavaScript object, you can convert the object into JSON, and send it to a server:

Input:-
<!DOCTYPE html>
<html>
<body>

<h2>This example is to convert a JavaScript object into a JSON string, and send it to the server.</h2>

<script>
var obj = { name: "Steve", age: 35, city: "USA" };
var myJson = JSON.stringify(obj);
window.location = "demo.php?x=" + myJson;
</script>

</body>
</html>

Output (Before json code execution):-

Output (After json code execution the user will be redirected to demo.php):-

Receiving Data

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

Input:-
<!DOCTYPE html>
<html>
<body>

<h2>This example is to convert a string written in JSON format, into a JavaScript object.</h2>

<p id="result"></p>

<script>
var myJson = '{"name":"Steve", "age":25, "city":"USA"}';
var obj = JSON.parse(myJson);
document.getElementById("result").innerHTML = obj.name;
</script>

</body>
</html>

Output :-