How to Parse JSON String into PHP Array or Object

Parsing a JSON string into a PHP array or object is a fundamental task when working with modern web applications and APIs. This guide demonstrates how to use PHP’s built-in json_decode() function to safely and efficiently convert JSON data into usable PHP variables, explaining how to target both standard objects and associative arrays.

The json_decode() Function

In PHP, the standard tool for parsing JSON is the json_decode() function. Its basic syntax is:

json_decode(string $json, ?bool $associative = null, int $depth = 512, int $flags = 0): mixed

By default, this function converts a JSON string into a PHP stdClass object. However, you can easily instruct it to return an associative array instead.


Option 1: Parse JSON into a PHP Object

If you only pass the JSON string to json_decode(), PHP will parse it into a standard object. You can then access the values using object notation (->).

$jsonString = '{"name": "John Doe", "email": "john@example.com", "age": 30}';

// Parse into an object
$userObject = json_decode($jsonString);

// Access properties
echo $userObject->name;  // Output: John Doe
echo $userObject->email; // Output: john@example.com

Option 2: Parse JSON into an Associative Array

To parse the JSON string into an associative array, pass true as the second argument to json_decode(). You can then access the values using standard array keys (['key']).

$jsonString = '{"name": "John Doe", "email": "john@example.com", "age": 30}';

// Parse into an associative array
$userArray = json_decode($jsonString, true);

// Access values
echo $userArray['name'];  // Output: John Doe
echo $userArray['email']; // Output: john@example.com

Error Handling

If the JSON string is malformed, json_decode() will return null. To ensure your application handles invalid JSON gracefully, you can use the JSON_THROW_ON_ERROR flag (available in PHP 7.3 and later) to throw a JsonException when parsing fails.

$invalidJson = '{"name": "John Doe", "email": "john@example.com"'; // Missing closing brace

try {
    $data = json_decode($invalidJson, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    echo "Parsing failed: " . $e->getMessage();
}