JavaScript JSON
14 April 2025 | Category: JavaScript
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and easy for machines to parse and generate. Itâs widely used for sending and receiving structured data, especially in web applications and APIs.
đŚ What is JSON?
- JSON is a text format for storing and transporting data.
- It is language-independent but uses a syntax similar to JavaScript object literals.
- Commonly used to exchange data between a server and a web application.
đ¤ JSON Syntax Rules
JSON data is written in key/value pairs:
{
"name": "Alice",
"age": 25,
"isStudent": false
}
â Rules:
- Data is enclosed in curly braces
{}
- Keys are strings (must be in double quotes
""
) - Values can be:
- String
- Number
- Boolean
- Array
- Object
null
đĄ JSON vs JavaScript Objects
Feature | JSON | JavaScript Object |
---|---|---|
Quotes | Keys must be in "double quotes" | Keys can be unquoted |
Functions | Not allowed | Allowed |
Comments | Not allowed | Allowed |
Trailing commas | Not allowed | Allowed |
đ Working with JSON in JavaScript
1. â Convert JavaScript Object to JSON
const user = {
name: "John",
age: 30,
hobbies: ["reading", "gaming"]
};
const jsonString = JSON.stringify(user);
console.log(jsonString);
// Output: {"name":"John","age":30,"hobbies":["reading","gaming"]}
2. â Convert JSON to JavaScript Object
const jsonStr = '{"name":"John","age":30,"hobbies":["reading","gaming"]}';
const userObj = JSON.parse(jsonStr);
console.log(userObj.name); // John
đŹ Real-World Use Case: Fetching JSON from an API
fetch('https://api.example.com/user')
.then(response => response.json())
.then(data => {
console.log(data);
});
Here, the response is typically in JSON format, and we parse it using .json()
to convert it into a usable JavaScript object.
đ Common Mistakes
â Forgetting to quote property names:
// Wrong
{ name: "John" }
// Correct
{ "name": "John" }
â Adding trailing commas:
// Wrong
{ "name": "John", }
// Correct
{ "name": "John" }
â Using single quotes:
// Wrong
{ 'name': 'John' }
// Correct
{ "name": "John" }
đ JSON Data Types
JSON Type | Example |
---|---|
String | "Hello" |
Number | 42 , 3.14 |
Boolean | true , false |
Object | { "a": 1, "b": 2 } |
Array | [1, 2, 3] |
Null | null |
đ§ When to Use JSON
- Communicating between frontend and backend
- Storing data in localStorage or files
- Config files (e.g.,
package.json
,.eslintrc.json
) - APIs (RESTful APIs use JSON by default)
đ Summary
- JSON is a text-based format for representing structured data.
- Use
JSON.stringify()
to convert objects to JSON. - Use
JSON.parse()
to convert JSON strings to JavaScript objects. - Essential for data exchange in web development.