JSON (JavaScript Object Notation) is a lightweight data format for storing and exchanging data. It is widely used to send data between a server and a client. JSON is simple, language-independent, and easy to understand.
- JSON stands for JavaScript Object Notation.
- It is a lightweight, text-based data interchange format.
- It is language-independent, meaning it can be used with most programming languages.
- JSON is derived from JavaScript but can be used with any programming language.
- JSON is "self-describing," making it human-readable.
Here is an example of JSON that defines an employee object containing an array of three employee records:
{
"employees": [
{ "firstName": "Amit", "lastName": "Kumar" },
{ "firstName": "Jay", "lastName": "Sharma" },
{ "firstName": "Mohit", "lastName": "Patel" }
]
}
JSON Syntax
JSON syntax is derived from JavaScript objects. Here are the rules:
- Data is written as name/value pairs (e.g., "name": "Mohit").
- Objects are enclosed in curly braces {}.
- Arrays are enclosed in square brackets [].
- Strings are wrapped in double quotes.
- Data values can be strings, numbers, booleans, arrays, objects, or null.
Converting JSON Text to a JavaScript Object
You can use the JSON.parse() method to convert a JSON string into a JavaScript object.
const jsonStr = `{
"emp": [
{ "firstName": "Amit", "lastName": "Kumar" },
{ "firstName": "Jay", "lastName": "Sharma" },
{ "firstName": "Mohit", "lastName": "Patel" }
]
}`;
const obj = JSON.parse(jsonStr);
console.log(obj.emp[1].firstName);
Output
Jay
Displaying JSON Data in HTML
<p id="demo"></p>
<script>
const s = `{
"emp": [
{ "firstName": "Amit", "lastName": "Kumar" },
{ "firstName": "Jay", "lastName": "Sharma" },
{ "firstName": "Mohit", "lastName": "Patel" }
]
}`;
const obj = JSON.parse(s);
document.getElementById("demo").innerHTML =
obj.emp[1].firstName + " " + obj.emp[1].lastName;
</script>
Converting a JavaScript Object to JSON
To send data to a server, you need to convert a JavaScript object to a JSON string using JSON.stringify().
const obj = { fname: "Mohit", lname: "Kumar", age: 30 };
const jsonStr = JSON.stringify(obj);
console.log(jsonStr);
Output
{"fname":"Mohit","lname":"Kumar","age":30}
JSON Objects
JSON objects are collections of key/value pairs enclosed in curly braces {}.
{
"fName": "Mohit",
"lName": "Kumar",
"age": 30
}
In JavaScript, you can access the data as follows:
const obj = { fName: "Mohit", lName: "Kumar", age: 30 };
console.log(obj.fName);
Output
Mohit
JSON Arrays
JSON arrays are collections of values enclosed in square brackets [].
{
"hobbies": ["reading", "coding", "traveling"]
}
You can access the data in JavaScript like this:
const obj = { hobbies: ["reading", "coding", "traveling"] };
console.log(obj.hobbies[1]);
Output
coding