JSON (JavaScript Object Notation) is a plain-text format for sending and storing data. Despite the name, nearly every programming language can read and write it, and almost every web API uses it.
{
"name": "Isha",
"age": 29,
"active": true,
"skills": ["php", "sql"],
"address": {
"city": "Pune",
"postcode": "411001"
},
"manager": null
}
Why JSON matters in PHP
- A JavaScript front end asks your PHP code for data, and you answer in JSON.
- A mobile app talks to your server with JSON.
- You call other services (payments, maps, weather) and read their JSON replies.
- You store settings or flexible data in a JSON file or column.
The syntax
JSON has only a few building blocks.
| JSON | Example | PHP equivalent |
|---|---|---|
| Object | {"name": "Ana"} | Associative array (or stdClass) |
| Array | [1, 2, 3] | Indexed array |
| String | "hello" | string |
| Number | 42, 3.14 | int or float |
| Boolean | true, false | bool |
| Null | null | null |
The rules (stricter than PHP)
- Strings use double quotes only.
'single'is invalid. - Keys must be strings in double quotes.
- No trailing commas, no comments.
- No
undefined, no functions, no dates (dates are written as strings).
<?php
var_dump(json_decode('{"name": "Ana"}', true));
var_dump(json_decode("{'name': 'Ana'}", true)); // single quotes: invalid
array(1) {
["name"]=>
string(3) "Ana"
}
NULL
Reading and writing it
PHP has two main functions, covered in the next lessons.
json_encode()turns a PHP value into a JSON string.json_decode()turns a JSON string into a PHP value.
<?php
$data = ["name" => "Ana", "skills" => ["php", "sql"]];
$json = json_encode($data);
echo $json . "\n";
$back = json_decode($json, true);
echo $back["skills"][1];
{"name":"Ana","skills":["php","sql"]}
sql
JSON vs XML vs CSV
| Format | Good for |
|---|---|
| JSON | APIs, settings, nested data |
| XML | Older systems, documents with a strict structure |
| CSV | Flat tables, spreadsheet exchange |
MIME type
When a server sends JSON, it sets the header Content-Type: application/json. See Building a JSON Response.
Pretty or compact
Both of these are the same data. APIs usually send the compact form to save bytes. A pretty form is for people.
Why this matters in WordPress and Laravel
/wp-json/wp/v2/posts) and Laravel API routes both speak JSON. A WordPress block editor page talks to the server in JSON all the time.