What is JSON?
JSON stands for JavaScript Object Notation. It is a way of representing a list of data like a list of objects. An object has its own set of properties and their corresponding values, JSON follows the same format to represent data in a text format.
Syntax of JSON
We can assign a JSON Object to a JavaScript variable or JSON objects can be saved inside a text file with .json extension. Syntax of defining a JSON object as a JavaScript variable is as shown below:
Syntax of defining JSON variables in JavaScript |
Purpose of JSON
JSON data is mainly used to exchange data in between applications just like we use XML data. The JSON format is much easier to parse than the XML data format.
Example of JSON Data
A simple example of JSON can be as shown below:
An Example of JSON data |
This is a simple example. If you want to see more examples, generate JSON data from www.json-generator.com. This is an online tool that generates random JSON data.
How to parse JSON Data
Now, let's see how to parse JSON data. I have generated JSON data from www.json-generator.com for this example.
Below is the JavaScript function that parses the JSON data and prints each of the attributes and values. This function can be used to perform any of the other operations with JSON data other than just printing them. Here is the jsFiddle code for your reference.
A function that prints the JSON data |
This function takes a javascript object as an argument so it is necessary to convert the JSON object that we have into the JavaScript object. It can be done as shown below:
Converting JSON to Object in JavaScript |
This way any JSON data with nested objects can be parsed in JavaScript. For any queries, you can write to [email protected]. To get notified for the releases, subscribe through email. If you found this article useful, please share it. Thank you 😊.