JSON (JavaScript Object Notation) is a lightweight data format for storing and exchanging data. It is easy to read and write for humans and machines. JSON is commonly used in APIs to send and receive data between a client and a server.
Sample:
{
"name": "Ashutosh",
"age": 25,
"isDeveloper": true,
"skills": ["JavaScript", "C#", "SQL"],
"address": {
"city": "Prayagraj",
"country": "India"
},
"experience": null
}
JSON Data Types
JSON supports six data types:
Data Types | Description | Examples |
String | Sequence of characters enclosed in double quotes | "JavaScript" |
Number | Integer or floating-point number | 25 , 3.14 |
Boolean | It represents True or False values | true , false |
Array | It represents Ordered list of values | ["C#", "JavaScript", "SQL"] |
Object | Key-value pairs like a dictionary | {"city": "Prayagraj", "country": "India"} |
Null | It represents an empty or unknown value | null |
A. JSON String (Text Data)
Strings in JSON must be enclosed in double quotation marks (" "), while single quotation marks (' ') are also allowed in JavaScript.
{
"language": "JavaScript"
}
B. JSON Number (Integer & Floating Point)
JSON supports integers and floating-point numbers without quotation marks.
{
"age": 25,
"price": 99.99
}
C. JSON Boolean (true
or false
)
The boolean datatype values represent true or false.
{
"isStudent": false,
"isVerified": true
}
D. JSON Array (List of Values)
An array in JSON is an ordered list of values. It can contain strings, numbers, objects, or other arrays.
{
"skills": ["JavaScript", "C#", "SQL"]
}
E. JSON Object (Key-Value Pairs)
An object is a collection of key-value pairs, similar to a JavaScript object.
{
"address": {
"city": "Prayagraj",
"country": "India"
}
}
F. JSON Null (Empty Value)
The null
represents an empty or missing value.
{
"experience": null
}
Parsing and Stringifying JSON in JavaScript
Convert JSON to JavaScript Object (JSON.parse()
)
let jsonString = '{"name": "Ashutosh", "age": 25, "isDeveloper": true}';
let jsonObject = JSON.parse(jsonString);
console.log(jsonObject.name); // Output: Ashutosh
Convert JavaScript Object to JSON (JSON.stringify()
)
let user = { name: "Ashutosh", age: 25, isDeveloper: true };
let jsonData = JSON.stringify(user);
console.log(jsonData); // Output: '{"name":"Ashutosh","age":25,"isDeveloper":true}'
Key JSON Rules & Best Practices
- Use double quotes
("")
for keys and strings. - Numbers and booleans should not be in quotation marks.
- Objects should use
{}
and arrays should use[]
. - Values can be nested objects or arrays.
- Use
null
for missing or unknown values. - Always parse (
JSON.parse()
) or stringify (JSON.stringify()
) when handling JSON in JavaScript
Thanks!
Also, Read: Explain the JavaScript AJAX Response
Leave Comment