JSON in JavaScript
JSON stands for JavaScript Object Notation. It is a lightweight format commonly used for storing and exchanging data between applications.
What is JSON?
JSON is a text-based data format that represents information using key-value pairs and arrays.
JSON is widely used when JavaScript applications communicate with web servers and APIs.
Simple Definition
JSON is a lightweight format used to represent and exchange structured data.
JSON is commonly used for structured data exchange between applications.
JSON Structure
A JSON object is written using curly braces. Data is represented using key-value pairs.
{
"name": "Rahul",
"age": 25,
"course": "JavaScript"
}
name → Rahul
age → 25
course → JavaScript
Example 1: JSON.stringify()
The JSON.stringify() method converts a JavaScript object into a JSON string.
var student = {
name: "Rahul",
age: 25
};
var jsonData = JSON.stringify(student);
console.log(jsonData);
{"name":"Rahul","age":25}
Example 2: JSON.parse()
The JSON.parse() method converts a JSON string into a JavaScript object.
var jsonData =
'{"name":"Rahul","age":25}';
var student = JSON.parse(jsonData);
console.log(student.name);
Rahul
Example 3: JSON Array
JSON can also represent arrays containing multiple values.
var students = [
"Rahul",
"Priya",
"Amit"
];
var jsonData = JSON.stringify(students);
console.log(jsonData);
["Rahul","Priya","Amit"]
Important Points
• JSON stands for JavaScript Object Notation.
• JSON is commonly used for data exchange.
• JSON.stringify() converts an object into a JSON string.
• JSON.parse() converts JSON text into a JavaScript object.
• JSON supports objects, arrays, strings, numbers, booleans and null.
Summary
JSON provides a simple and standard way to represent structured data. JavaScript provides JSON.stringify() and JSON.parse() for converting between JavaScript objects and JSON text.