JS JSON
JSON Intro
JSON (JavaScript Object Notation) is a lightweight data format used for data exchange between client and server. It is text-based and easy for both humans and machines to read.
JSON is not JavaScript code — it is a data format.
JSON Syntax
JSON syntax rules:
- Data is in name/value pairs
- Data is separated by commas
- Objects are wrapped in { }
- Arrays are wrapped in [ ]
- Keys must be double-quoted strings
{
"name": "Ozan",
"age": 30,
"active": true
}
JSON vs XML
- JSON is lighter and easier to parse
- JSON maps directly to JavaScript objects
- XML supports attributes and complex schemas
// JSON
{ "name": "Ali" }
// XML
<user>
<name>Ali</name>
</user>
Modern web APIs almost always use JSON.
JSON Data Types
JSON supports:
- String
- Number
- Object
- Array
- Boolean
- null
JSON does NOT support:
- Functions
- undefined
- Comments
JSON Parse
JSON.parse() converts JSON text into a JavaScript object.
const text = "{ "name": "Jane", "age": 25 }";
const obj = JSON.parse(text);
console.log(obj.name);
With reviver function:
const data = JSON.parse(text, (key, value) => {
if (key === "age") return value + 1;
return value;
});
JSON Stringify
JSON.stringify() converts a JavaScript object into JSON text.
const user = { name: "Ali", age: 30 };
const json = JSON.stringify(user);
console.log(json);
Pretty formatting:
console.log(JSON.stringify(user, null, 2));
Replacer example:
const filtered = JSON.stringify(user, (key, value) => {
if (key === "age") return undefined;
return value;
});
JSON Objects
JSON objects become normal JavaScript objects after parsing.
const obj2 = JSON.parse("{ "id": 1, "name": "Test" }");
console.log(obj2.id);
Be careful: methods are lost when converting to JSON.
JSON Arrays
JSON arrays map directly to JavaScript arrays.
const list = JSON.parse("[1, 2, 3, 4]");
console.log(list[0]);
Array of objects:
const users = JSON.parse("[{"id":1},{"id":2}]");
console.log(users[1].id);
JSON Server
Servers typically return JSON with the correct content type header:
Content-Type: application/json
Fetch example:
fetch("/api/users")
.then(res => res.json())
.then(data => console.log(data));
JSON PHP
In PHP, use json_encode() and json_decode().
<?php
header('Content-Type: application/json; charset=utf-8');
$data = [
'id' => 1,
'name' => 'Ozan'
];
echo json_encode($data);
Decode JSON in PHP:
$json = "{"id":1,"name":"Ali"}";
$obj = json_decode($json, true);
JSON HTML
Use JSON data to update the DOM dynamically.
async function loadUsers() {
const res = await fetch("/api/users");
const users = await res.json();
const list = document.querySelector("#users");
list.innerHTML = users
.map(u => `<li>${u.name}</li>`)
.join("");
}
JSON JSONP
JSONP (JSON with Padding) was an old technique to bypass cross-domain restrictions before CORS existed.
It works by injecting a <script> tag. Today, use CORS instead.
function handleData(data) {
console.log(data);
}
// Example idea (legacy):
// <script src="https://api.example.com?callback=handleData"></script>
Modern advice: Avoid JSONP. Use Fetch + proper CORS headers.
Best Practices
- Always validate server responses
- Handle parsing errors
- Never trust client-side JSON blindly
- Use HTTPS for API communication
Next Step
You have now completed the full JS Advanced data layer: AJAX + JSON + Web APIs.