PHP JSON
JSON is a lightweight, text-based data format that PHP can convert to and from its own arrays and objects using json_encode() and json_decode().
What JSON is used for
JSON (JavaScript Object Notation) is the common language that web applications use to exchange structured data. When a PHP backend answers a request from JavaScript, a mobile app, or another API, it usually sends the reply as JSON. PHP includes two built-in functions that handle the translation: json_encode() turns PHP data into a JSON string, and json_decode() turns a JSON string back into PHP data.
Because JSON is plain text, it travels easily over HTTP and is readable by almost every programming language. PHP arrays map neatly onto JSON: an indexed array becomes a JSON array, and an associative array becomes a JSON object.
Encoding PHP data to JSON
<?php
$person = [
"name" => "Ada Lovelace",
"age" => 36,
"languages" => ["English", "French"],
"active" => true
];
$json = json_encode($person, JSON_PRETTY_PRINT);
echo $json;
?>Decoding JSON into PHP
json_decode() reads a JSON string and rebuilds it as PHP data. By default a JSON object becomes a PHP object with properties, so you read it with the arrow syntax. If you pass true as the second argument, you get an associative array instead, which many developers find easier to work with.
Decoding to an object and to an array
<?php
$json = '{"name":"Ada","age":36,"languages":["English","French"]}';
// As an object (default)
$obj = json_decode($json);
echo $obj->name; // Ada
echo $obj->languages[0]; // English
// As an associative array
$arr = json_decode($json, true);
echo $arr["age"]; // 36
?>Handling errors
If the input string is not valid JSON, json_decode() returns null. Since a valid JSON value can also literally be null, the safest way to detect a real problem is to check json_last_error(). On modern PHP you can also pass the JSON_THROW_ON_ERROR flag so a failure raises a JsonException you can catch.
Detecting invalid JSON
<?php
$badJson = '{"name": "Ada", }'; // trailing comma is invalid
$data = json_decode($badJson, true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo "Could not parse JSON: " . json_last_error_msg();
} else {
echo $data["name"];
}
?>- Associative arrays become JSON objects; indexed arrays become JSON arrays.
- Pass true to json_decode() when you prefer arrays over objects.
- Always check json_last_error() or use JSON_THROW_ON_ERROR when the input is not trusted.
- JSON keys and string values must use double quotes, and trailing commas are not allowed.
Exercise: PHP JSON
What does json_encode() do when given a PHP associative array?