JSON Object Literals
15 April 2025 | Category: JavaScript
A JSON Object Literal is a structured data format that represents data using key-value pairs, similar to JavaScript objects — but with stricter rules.
✅ JSON is a text-based format for storing and exchanging data, while object literals are JavaScript code.
📘 Example: JSON Object Literal
{
"name": "Alice",
"age": 25,
"isStudent": false,
"skills": ["HTML", "CSS", "JavaScript"],
"address": {
"city": "Delhi",
"zip": "110001"
}
}
JSON object literal is usually written inside curly braces
{}
with key-value pairs separated by commas.
🧠 JSON Object Literal vs JavaScript Object
Feature | JSON | JavaScript Object |
---|---|---|
Quotes for keys | Required (double quotes) | Optional |
Quotes for strings | Must use double quotes | Can use single or double quotes |
Function support | ❌ Not allowed | ✅ Allowed |
Data types supported | string, number, boolean, null, array, object | All JS types |
Example:
// JSON - Strict format
const jsonData = '{ "name": "Alice", "age": 25 }';
// JS Object - More flexible
const jsObj = { name: "Alice", age: 25 };
✅ Using JSON Object Literals in Code
You can convert a JSON string to a JavaScript object using JSON.parse()
:
const jsonString = '{ "name": "Alice", "age": 25 }';
const userObj = JSON.parse(jsonString);
console.log(userObj.name); // Output: Alice
You can also convert a JavaScript object to a JSON string using JSON.stringify()
:
const user = { name: "Bob", age: 30 };
const jsonStr = JSON.stringify(user);
console.log(jsonStr);
// Output: {"name":"Bob","age":30}
✅ Data Types Allowed in JSON Object Literals
- String
"name": "John"
- Number
"age": 30
- Boolean
"isActive": true
- Null
"spouse": null
- Array
"skills": ["HTML", "CSS"]
- Object
"address": { "city": "Delhi" }
⚠️ JSON Object Literal Rules
- Keys must be in double quotes.
- Strings must use double quotes.
- No functions or comments allowed.
- Values must be one of the allowed data types.
🔚 Summary
- JSON Object Literals represent structured data in key-value format.
- They are used widely in APIs, configurations, and data exchange.
- They follow strict syntax compared to JavaScript objects.