JSON Explained: Syntax, JSON.parse, JSON.stringify and PHP
What is JSON?
JSON (JavaScript Object Notation) is a lightweight text format for exchanging structured data. It represents objects as name and value pairs in curly braces and lists as values in square brackets. Although its syntax comes from JavaScript, it is language-independent: browsers, PHP, Python and almost every API can read and write it, which makes it the usual format for web APIs.
JSON syntax rules and data types
JSON is defined by RFC 8259 and the ECMA-404 standard. It has six value types and a short list of strict rules.
| Type | Example |
|---|---|
| String | "Pune", always in double quotes |
| Number | 42, -3.5, 1.2e3 |
| Boolean | true or false |
| Null | null |
| Object | {"name": "Asha", "age": 21} |
| Array | ["html", "css", "js"] |
{
"course": "PHP Foundation",
"online": true,
"modules": [
{ "id": 1, "title": "Variables and types", "hours": 4 },
{ "id": 2, "title": "Forms and validation", "hours": 6 }
],
"mentor": null
}- Property names and strings must use double quotes; single quotes are invalid.
- No trailing commas after the last item in an object or array.
- No comments, no
undefined, no functions and no dates as a special type. NaN,Infinityand leading zeros such as07are not allowed.- Text must be UTF-8 when exchanged between systems, and special characters in strings are escaped with a backslash, such as
\nor\".
You will meet JSON well beyond API responses: package.json in JavaScript projects, composer.json in PHP projects, JSON-LD structured data in page heads, browser localStorage values and log files. The same strict rules apply in every case, so a single misplaced comma can stop a build or an API call. A quick way to find such errors is to paste the text into your browser console inside JSON.parse() and read the position in the error message.
Converting JSON in JavaScript: JSON.parse and JSON.stringify
JSON.parse() turns a JSON string into JavaScript values and throws a SyntaxError if the text is invalid. JSON.stringify() does the reverse.
const text = '{"name":"Ravi","marks":[78,91],"joined":"2026-07-01"}';
let student;
try {
student = JSON.parse(text);
} catch (err) {
console.error('Invalid JSON:', err.message);
}
JSON.stringify(student); // compact string
JSON.stringify(student, null, 2); // indented with 2 spaces
JSON.stringify(student, ['name']); // only the listed keys
JSON.stringify({ a: undefined, f() {}, d: new Date(0), n: NaN });
// '{"d":"1970-01-01T00:00:00.000Z","n":null}'
// A reviver turns date strings back into Date objects
const parsed = JSON.parse(text, (key, value) =>
key === 'joined' ? new Date(value) : value);Note how stringify drops undefined and functions, converts dates to ISO strings via toJSON() and turns NaN into null. A JSON.parse(JSON.stringify(obj)) round trip is therefore a lossy copy; use structuredClone() for deep copies.
JSON in PHP: json_encode and json_decode
By default, json_encode() returns false and json_decode() returns null on failure, which is easy to miss because null is also valid JSON. Pass JSON_THROW_ON_ERROR (available since PHP 7.3) so problems throw a JsonException you can catch.
<?php
declare(strict_types=1);
$course = [
'title' => 'PHP Foundation',
'city' => 'Bengaluru',
'tags' => ['php', 'mysql'],
'price' => null,
'url' => '/courses/php-foundation-course/',
];
$json = json_encode(
$course,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
);
try {
// true = associative arrays instead of stdClass objects
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
echo $data['tags'][0]; // php
} catch (JsonException $e) {
error_log('Bad JSON: ' . $e->getMessage());
}
var_dump(json_validate('{"ok": true}')); // bool(true), PHP 8.3+| Flag | Effect |
|---|---|
JSON_THROW_ON_ERROR | Throws JsonException instead of returning false or null |
JSON_UNESCAPED_UNICODE | Keeps characters such as Hindi text readable instead of \u escapes |
JSON_UNESCAPED_SLASHES | Writes / instead of \/ |
JSON_PRETTY_PRINT | Indents output for logs and config files |
JSON_FORCE_OBJECT | Encodes arrays as objects, so an empty array becomes {} |
A PHP list such as [1, 2] becomes a JSON array, while an array with string or non-sequential keys becomes an object. An empty array encodes as []; if your API promises an object, encode new stdClass() or use JSON_FORCE_OBJECT. For arrays in general, see the PHP arrays guide.
Sending JSON from a PHP endpoint, step by step
- Collect the data into an array, using only the fields the client needs.
- Set the status code with
http_response_code(). - Send
Content-Type: application/json; charset=utf-8before any output. - Echo
json_encode($data, JSON_THROW_ON_ERROR)and stop. - On the client, check
response.ok, then callresponse.json().
<?php
// api/course.php
header('Content-Type: application/json; charset=utf-8');
http_response_code(200);
echo json_encode(['id' => 3, 'title' => 'Advanced PHP'], JSON_THROW_ON_ERROR);To read JSON sent in a request body, use file_get_contents('php://input') and decode it; $_POST is only filled for form-encoded bodies.
<?php
// api/save.php: accept a JSON body
header('Content-Type: application/json; charset=utf-8');
try {
$input = json_decode(file_get_contents('php://input'), true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException) {
http_response_code(400);
echo json_encode(['error' => 'Request body must be valid JSON'], JSON_THROW_ON_ERROR);
exit;
}
if (!is_array($input) || !is_string($input['title'] ?? null)) {
http_response_code(422);
echo json_encode(['error' => 'title is required'], JSON_THROW_ON_ERROR);
exit;
}
echo json_encode(['saved' => $input['title']], JSON_THROW_ON_ERROR);Separate status codes for malformed JSON (400) and well-formed but incomplete data (422) help the client show the right message. The Fetch API guide shows the browser side of this exchange.
Good JSON practices and security
- Treat decoded JSON as untrusted input: validate types, required fields and lengths before using it.
- Never parse JSON with
eval(); useJSON.parse()orjson_decode(). - Keep key naming consistent across an API, for example always
snake_caseor alwayscamelCase. - Send money as integers in the smallest unit, such as paise, or as strings, to avoid floating-point rounding.
- Very large integers beyond about 9 quadrillion lose precision in JavaScript, so send IDs that big as strings.
- Leave sensitive fields, such as password hashes, out of the arrays you encode.
- Send dates as ISO 8601 strings, such as
2026-11-10T09:30:00+05:30, so every client can parse them without guessing the time zone.
Practical exercise: a JSON course catalogue
Store three courses in a PHP array and expose them through catalogue.php, then render them on a page.
- Encode the array with
JSON_THROW_ON_ERRORandJSON_UNESCAPED_UNICODE, including one title in Hindi. - Fetch the file in the browser and build a list with
textContent. - Add a
save.phpendpoint that decodes a JSON body, rejects missing fields with status 422 and returns the saved item. - Deliberately send invalid JSON, such as a trailing comma, and confirm the endpoint responds with status 400 and a JSON error message.
You are done when the Hindi title displays correctly, invalid input never produces a PHP warning, and every response has a JSON content type. Working with data this way is covered in SkillNewton's PHP foundation course, and a broader introduction sits in our APIs explainer.
Common mistakes
- Using single quotes or trailing commas, which make the whole document invalid.
- Calling
json_decode()withoutJSON_THROW_ON_ERRORand treatingnullas success. - Forgetting the second argument of
json_decode()and then trying to use the result as an array. - Echoing PHP warnings or whitespace before the JSON, which breaks parsing in the browser.
- Expecting
JSON.stringify()to keepundefined, functions or Date objects.
Frequently asked questions
Is JSON the same as a JavaScript object?
No. JSON is a text format with stricter rules. A JavaScript object is a live value in memory that can hold functions, undefined and other types JSON cannot represent.
What is the MIME type for JSON?
It is application/json. JSON text exchanged between systems must be encoded as UTF-8.
Can JSON have comments?
Standard JSON cannot. Some tools accept variants such as JSONC for configuration files, but APIs and JSON.parse() expect strict JSON.
Should I use JSON or XML?
For web APIs and JavaScript front ends, JSON is simpler and far more common. XML still appears in sitemaps, RSS feeds and some older enterprise systems.