Alexa Metrics

JavaScript intermediate series: the JSON

2018-12-13
image of icon showing JSON in JavaScript

JavaScript is one of the most widely-used languages today. It is used in many web applications, which means that we encounter it many times a day since web applications are embedded in our daily lives.


What is JSON?

Web applications can run from a mobile application or a website. Either way, data is exchanged between the website and the server in the form of text. This is the reason we need JSON, which stands for JavaScript Object Notation.

JSON is a method of storing and exchanging data between web applications and the servers that host them. It is a form of text written in JavaScript. Almost any JavaScript object can be converted into JSON to be sent to the server and vice-versa.


How can we send data in JSON?

If you want to send data that has been stored previously in a JavaScript object, you can convert it into JSON and send it to the server:

var student = {name: "John", age: 10};

var my_JSON = JSON.stringify(student);

window.location = "demo_json.php?x=" + my_JSON;


How can we receive data in JSON?

What about going the other way? When you receive data in the JSON format, you convert it back to a JavaScript object:

var my_JSON = '{"name":"John", "age":10}';

var student = JSON.parse(my_JSON);

document.getElementById("demo").innerHTML = student.name;


What about storing data?

How can we store data in JSON format? As we discussed earlier, data must be text and stored in a specific format:

student = {name: "John", age: 10};

my_JSON = JSON.stringify(student);

localStorage.setItem("testJSON", my_JSON);


When you want to get your data back, you can do the following:

text = localStorage.getItem("testJSON");

obj = JSON.parse(text);

document.getElementById("demo").innerHTML = obj.name;


JSON’s flexibility:

One thing to keep in mind is that JSON is a writing format that is not restricted to JavaScript. JSON can be used and interpreted by other languages as well.

JavaScript is unique because it has built-in functions to convert JSON back and forth from a text. For example, JSON.parse() is a special command that is not necessarily found in other languages.

JSON can be used to break down almost any piece of data you have. That’s why it has grown to be so widely-used today. It is very important that you know how to parse a JSON and understand its format if you like to work with web applications.


JSON itself has many applications, but make sure you’re caught up with JavaScript first. Start your learning journey today with RoboGarden and register for free.


JavaScript Series

RELATED BLOGS

Start JavaScript coding

Let's start JavaScript coding with RoboGarden learning journey.

Canada Flag Privacy Policy Terms of Use
Got an invite