PHP example

How to parse JSON into an array in PHP

9 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Pass true as the second argument: $data = json_decode($json, true); returns nested associative arrays, so you read values with $data['user']['name']. Without true you get stdClass objects, and array syntax on them throws Cannot use object of type stdClass as array. Add JSON_THROW_ON_ERROR so bad input throws a JsonException instead of returning null.

json_decode() is the one function PHP has for reading JSON, and most of the trouble with it comes from its defaults: objects come back as stdClass instead of arrays, and broken input returns null with no warning. The sections below decode a realistic API response into arrays, read the object form when you have to, catch errors properly, check whether a string is JSON at all, loop over keys you don't know in advance, and cover the edge cases that change your data on the way in, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1json_decode($json, true): an associative arrayRecommended

The second parameter of json_decode() is $associative. Set it to true and every JSON object becomes a PHP associative array, all the way down, while JSON arrays become ordinary lists. You then use the same square-bracket syntax and array functions as for any other array, and the ?? operator gives a default for a key the response doesn't include, without a warning.

decode_array.php
<?php

$json = '{
    "id": 4182,
    "login": "mira-k",
    "verified": true,
    "score": 97.5,
    "manager": null,
    "address": {"city": "Lisbon", "zip": "1100-148"},
    "roles": ["admin", "editor"],
    "repos": [
        {"name": "api-client", "stars": 214},
        {"name": "dotfiles", "stars": 9}
    ]
}';

// true = decode JSON objects as associative arrays
$user = json_decode($json, true);

echo $user['login'], "\n";
echo $user['address']['city'], "\n";
echo $user['roles'][0], "\n";
echo $user['repos'][1]['name'], ' has ', $user['repos'][1]['stars'], " stars\n";

// Missing keys: ?? gives a default without a warning
echo $user['address']['country'] ?? 'unknown', "\n";
echo $user['manager'] ?? 'no manager', "\n";

// JSON types map to PHP types
var_dump($user['id'], $user['verified'], $user['score'], $user['manager']);

// Arrays of objects work with the usual array functions
$names = array_column($user['repos'], 'name');
echo implode(', ', $names), "\n";
echo 'Total stars: ', array_sum(array_column($user['repos'], 'stars')), "\n";

Output

Nested values are one bracket per level: $user['address']['city'] prints Lisbon and $user['repos'][1]['name'] prints dotfiles. The var_dump shows the type mapping: a JSON whole number becomes int(4182), true becomes bool(true), a decimal becomes float(97.5) and null becomes NULL. Because the list of repos is a plain array of arrays, array_column pulls out api-client, dotfiles and the star counts sum to 223. The reverse direction, an array back to a JSON string, is covered in converting an array to JSON.

2The default: stdClass objects and the "Cannot use object" error

Call json_decode($json) with no second argument and each JSON object becomes a stdClass object, PHP's empty generic class. You read it with ->, not brackets. A key that isn't a valid PHP name, such as first-name or one starting with a digit, goes in braces: $user->{'first-name'}. Using array syntax on the object is the error behind one of the most viewed PHP questions on Stack Overflow.

decode_object.php
<?php

$json = '{"login": "mira-k", "first-name": "Mira", "2fa": true,
    "address": {"city": "Lisbon"}, "roles": ["admin", "editor"]}';

// No second argument: JSON objects become stdClass objects
$user = json_decode($json);

echo get_class($user), "\n";
echo $user->login, "\n";
echo $user->address->city, "\n";   // nested objects use -> too
echo $user->roles[0], "\n";        // JSON arrays are still PHP arrays

// Keys that are not valid PHP names need braces
echo $user->{'first-name'}, "\n";
var_dump($user->{'2fa'});

$key = 'login';
echo $user->$key, "\n";            // a key held in a variable

echo $user->address->zip ?? 'no zip', "\n";

// The classic mistake: array syntax on an object
try {
    echo $user['login'];
} catch (Error $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}

// A cast converts only the top level
$asArray = (array) $user;
echo $asArray['login'], "\n";
echo gettype($asArray['address']), "\n";

Output

Only JSON objects turn into objects: $user->roles[0] still uses brackets because roles was a JSON array. The try block catches what is normally fatal: $user['login'] throws Error: Cannot use object of type stdClass as array, and uncaught it ends the script with Fatal error: Uncaught Error: Cannot use object of type stdClass as array and exit code 255. The fix is true in the json_decode call (section 1), or -> everywhere. Casting with (array) is not a full fix: the last line prints object, because the nested address is still a stdClass. For converting objects you already have, see converting an object to an array.

3Catching invalid JSON with JSON_THROW_ON_ERROR

By default json_decode() returns null when the input is not valid JSON, which is also what it returns for the valid JSON text null, and it prints nothing. The old way to tell them apart is to call json_last_error() or json_last_error_msg() right after decoding. Since PHP 7.3 the cleaner option is the JSON_THROW_ON_ERROR flag, the fourth argument: bad input then throws a JsonException whose message and code say what went wrong. The third argument, the depth limit, must come first; 512 is its default.

decode_errors.php
<?php

// Without a flag, broken JSON and the valid JSON text null look the same
var_dump(json_decode('{"id": 1,}', true));
var_dump(json_decode('null', true));

// The old way to tell them apart: ask right after the call
json_decode('{"id": 1,}', true);
echo json_last_error(), ': ', json_last_error_msg(), "\n";

// PHP 7.3+: JSON_THROW_ON_ERROR makes bad input throw a JsonException
function parseJson(string $json): mixed
{
    return json_decode($json, true, 512, JSON_THROW_ON_ERROR);
}

$inputs = [
    'valid'          => '{"id": 1, "tags": ["a", "b"]}',
    'trailing comma' => '{"id": 1,}',
    'single quotes'  => "{'id': 1}",
    'cut off'        => '{"id": 1',
    'empty string'   => '',
    'bad UTF-8'      => "{\"name\": \"\xE9\"}",
    'null'           => 'null',
];

foreach ($inputs as $label => $input) {
    try {
        $data = parseJson($input);
        echo "$label: ", get_debug_type($data), "\n";
    } catch (JsonException $e) {
        echo "$label: JsonException ", $e->getCode(), ' ', $e->getMessage(), "\n";
    }
}

Output

The first two lines are both NULL, one from a trailing comma and one from real JSON, and json_last_error_msg() is the only way to learn that the first failed: 4: Syntax error. With the flag, every broken input throws. JSON is stricter than JavaScript: a trailing comma, single quotes and an empty string are all Syntax error (code 4), and text that isn't UTF-8, such as a Latin-1 é byte, is code 5, Malformed UTF-8 characters, possibly incorrectly encoded. The JSON text null decodes without an exception, so a null result now really means null. Catch JsonException, log the message, and return an error to the caller rather than carrying on with no data.

4Checking if a string is JSON: json_validate()

When you only need a yes or no, PHP 8.3 added json_validate(). It runs the same parser but doesn't build any arrays or objects, so it uses less memory than decoding, and it sets json_last_error_msg() like json_decode does. On older PHP, decode and compare json_last_error() with JSON_ERROR_NONE. If you are going to use the data anyway, skip the check and decode once with JSON_THROW_ON_ERROR: validating first parses the string twice.

validate.php
<?php

$inputs = [
    '{"ok": true}',
    '[1, 2, 3]',
    '"hello"',
    '42',
    'null',
    '{"ok": true',
    'hello',
    '',
];

// PHP 8.3+: json_validate() checks the syntax without building the value
foreach ($inputs as $input) {
    printf("%-15s %s\n", var_export($input, true),
        json_validate($input) ? 'valid' : 'invalid');
}
echo 'Last error: ', json_last_error_msg(), "\n";

// Before PHP 8.3: decode, then look at the error code
function isJson(string $s): bool
{
    json_decode($s);
    return json_last_error() === JSON_ERROR_NONE;
}
var_dump(isJson('{"ok": true}'), isJson('hello'));

// Valid JSON can be a bare number or string. If you need an object or
// a list, decode it and check that you got an array.
foreach (['{"ok": true}', '42'] as $input) {
    $data = json_decode($input, true);
    echo $input, ' -> ', is_array($data) ? 'array' : get_debug_type($data), "\n";
}

Output

"Valid JSON" is wider than most people expect: '"hello"', '42' and 'null' all pass, because a JSON document can be a single string, number or literal. A bare word like hello (no quotes) and the empty string fail, and Last error: Syntax error comes from the last failed check. The older isJson() helper gives the same answers. When the input must be an object or a list, test the decoded value with is_array(): 42 -> int shows why json_validate alone isn't enough. Checks like "starts with a brace" are not validation and let broken JSON through.

5Looping through dynamic keys

Many APIs use data as keys: a map of language names to byte counts, or user names to stats. You can't write those keys into your code, so loop with foreach ($data as $key => $value), which gives you each key and its value. array_keys() lists the keys alone. For data of unknown depth, a short recursive function visits every leaf. foreach also works on a stdClass object, where it walks the public properties.

dynamic_keys.php
<?php

// Keys you don't know in advance: a map of language => bytes
$json = '{
    "repo": "api-client",
    "languages": {"PHP": 48210, "JavaScript": 9120, "Shell": 640},
    "contributors": {
        "mira-k": {"commits": 312, "admin": true},
        "dev_ole": {"commits": 87, "admin": false}
    }
}';

$data = json_decode($json, true);

// foreach gives you each key and its value
foreach ($data['languages'] as $language => $bytes) {
    echo "$language: $bytes bytes\n";
}

foreach ($data['contributors'] as $login => $info) {
    $role = $info['admin'] ? 'admin' : 'member';
    echo "$login ($role) made {$info['commits']} commits\n";
}

echo implode(', ', array_keys($data['languages'])), "\n";

// Unknown depth: recurse and build a dotted path for every leaf
function walk(array $node, string $path = ''): void
{
    foreach ($node as $key => $value) {
        $here = $path === '' ? (string) $key : "$path.$key";
        if (is_array($value)) {
            walk($value, $here);
        } else {
            echo $here, ' = ', json_encode($value), "\n";
        }
    }
}

walk($data);

// The same foreach works on stdClass objects
$obj = json_decode($json);
foreach ($obj->contributors as $login => $info) {
    echo "$login: {$info->commits}\n";
}

Output

The keys come back in the order they appear in the JSON, so the first loop prints PHP: 48210 bytes, then JavaScript, then Shell. In the second loop each $info is itself an array, read with {$info['commits']} inside the string. walk() calls itself for every nested array and prints one line per value, such as contributors.mira-k.admin = true; passing each value through json_encode keeps strings quoted and booleans readable. The last loop gives the same mira-k: 312 from the object form, with -> for the inner values.

6Big integers, empty objects, numeric keys and depth

Decoding to arrays can change data in four ways worth knowing before they show up in production. A number too big for a PHP int becomes a float and loses digits; JSON_BIGINT_AS_STRING keeps it as a string. An empty JSON object {} and an empty list [] both become an empty PHP array, so the difference is gone when you encode it again. Object keys that look like whole numbers become integer array keys. And nesting deeper than the $depth argument fails.

edge_cases.php
<?php

// 1. Integers above PHP_INT_MAX become floats and lose digits
$json = '{"order_id": 12345678901234567890}';
var_dump(json_decode($json, true)['order_id']);
$data = json_decode($json, true, 512, JSON_BIGINT_AS_STRING);
var_dump($data['order_id']);

// 2. {} and [] both become an empty PHP array
$json = '{"settings": {}, "tags": []}';
$data = json_decode($json, true);
var_dump($data['settings'] === $data['tags']);
echo json_encode($data), "\n";        // the {} is now []
echo json_encode(json_decode($json)), "\n";   // objects keep it

// 3. Numeric object keys turn into integer array keys
var_dump(json_decode('{"10": "ten", "007": "bond"}', true));

// 4. The depth limit must be larger than the nesting
$deep = '{"a": {"b": {"c": 1}}}';
var_dump(json_decode($deep, true, 3));
echo json_last_error_msg(), "\n";
echo json_decode($deep, true, 4)['a']['b']['c'], "\n";

Output

The ID 12345678901234567890 is larger than PHP_INT_MAX, so the default decode gives float(1.2345678901234567E+19) and the last digits are lost; with JSON_BIGINT_AS_STRING it comes back intact as string(20). Treat IDs like that as strings from then on. The round trip prints {"settings":[],"tags":[]}: the empty object turned into a list, which can break an API that expects an object. Decoding without true keeps {}. The key "10" became the integer [10], while "007" stays a string because of its leading zero. Three nested objects fail at depth 3 with Maximum stack depth exceeded and need a depth of 4; the default of 512 is plenty for real data, and a lower value is a cheap guard against hostile input.

7Which should you use?

MethodResultOn bad inputBest for
json_decode($j, true, 512, JSON_THROW_ON_ERROR)ArraysThrows JsonExceptionMost code: decode and use the data
json_decode($j, true)ArraysReturns nullTrusted input; check json_last_error()
json_decode($j)stdClass objectsReturns nullKeeping {} vs [] for a round trip
json_validate($j)true / falsefalse, error via json_last_error_msg()Yes/no checks without the data (PHP 8.3+)
JSON_BIGINT_AS_STRINGBig ints as stringsn/aIDs larger than PHP_INT_MAX

Frequently asked questions

How do I make json_decode return an array instead of an object?

Pass true as the second argument: json_decode($json, true). Every JSON object, at every level, then becomes an associative array, and JSON arrays become lists. Passing the JSON_OBJECT_AS_ARRAY flag in the fourth argument does the same when the second argument is null.

How do I fix "Cannot use object of type stdClass as array"?

The value came from json_decode() without true, so it is a stdClass object and $data['key'] throws an Error. Either decode with json_decode($json, true) and keep the bracket syntax, or read the object with $data->key (and $data->{'odd-key'} for keys that are not valid PHP names). Casting with (array) converts only the top level.

Why does json_decode return null?

Either the input is not valid JSON or it is the JSON text null. Common causes are a trailing comma, single quotes, an empty string, a byte-order mark or text that is not UTF-8. Call json_last_error_msg() right after the call to see the reason (for example Syntax error), or pass JSON_THROW_ON_ERROR so the problem arrives as a JsonException.

What is the fastest way to check if a string is JSON in PHP?

On PHP 8.3 and later, json_validate($string) returns true or false without building the decoded value, so it saves memory on large input. On older versions, call json_decode($string) and check json_last_error() === JSON_ERROR_NONE. Note that "hello" (with quotes), 42 and null are all valid JSON; if you need an object or list, decode and check is_array().

How do I loop through a JSON object with unknown keys in PHP?

Decode it and use foreach ($data as $key => $value); it works on both the array form and a stdClass object. array_keys($data) gives just the keys. For nested data of unknown depth, write a recursive function that calls itself when is_array($value) is true.

Why did my large ID change after json_decode?

Integers larger than PHP_INT_MAX (9223372036854775807 on 64-bit PHP) are decoded as floats, which keep only about 17 significant digits. Pass JSON_BIGINT_AS_STRING in the fourth argument, for example json_decode($json, true, 512, JSON_BIGINT_AS_STRING), to get them as exact strings instead.

Run it yourself

Open any of these in the full PHP editor to tweak, run and share.

PHP playground