How to Parse JSON in PHP

← All guides

PHP has built-in json_decode and json_encode functions. Decode to associative arrays or stdClass objects, and encode with formatting flags.

Decode a JSON string

Pass true as the second argument to get an associative array instead of objects.

php
$text = '{"name":"Ada","roles":["admin","dev"]}';
$data = json_decode($text, true);
echo $data["name"];       // Ada
echo $data["roles"][0];   // admin

Encode to JSON

Use JSON_PRETTY_PRINT for readable output and JSON_UNESCAPED_UNICODE/SLASHES to keep text clean.

php
$obj = ["name" => "Ada", "active" => true];
echo json_encode($obj);
echo json_encode($obj,
    JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

Detect decode errors

json_decode returns null on failure; check json_last_error, or pass JSON_THROW_ON_ERROR (PHP 7.3+) to get an exception.

php
try {
    $data = json_decode($text, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    echo "Invalid JSON: " . $e->getMessage();
}

Frequently Asked Questions

By default json_decode returns stdClass objects. Pass true as the second argument to get associative arrays, which are usually easier to work with.

The input is invalid JSON or exceeds the nesting depth. Use JSON_THROW_ON_ERROR or json_last_error_msg() to see why.

Pass the JSON_UNESCAPED_SLASHES flag to json_encode so URLs stay readable.

Related Tools