Skip to content
Justice Tech School

JSON

json_encode turns arrays and objects into JSON text and json_decode reads it back (pass true to get arrays). JSON_PRETTY_PRINT formats the output. Always check json_last_error or use JSON_THROW_ON_ERROR.

Example
$data = ["name" => "Ada", "skills" => ["php", "sql"], "active" => true];
echo json_encode($data), "\n";
echo json_encode($data, JSON_PRETTY_PRINT), "\n";
$back = json_decode('{"x": 1, "list": [1, 2]}', true);
echo $back["list"][1], "\n";
try {
  json_decode("{bad}", false, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
  echo "Invalid JSON\n";
}

Result

{"name":"Ada","skills":["php","sql"],"active":true}
{
    "name": "Ada",
    "skills": [
        "php",
        "sql"
    ],
    "active": true
}
2
Invalid JSON

Exercise

Turn an array into JSON.

echo ($data);

Quiz Test

What does json_decode($s, true) return?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.