Coder Perfect

In PHP, json encode/json decode returns stdClass rather than Array.

Problem

Take a look at the following script:

$array = array('stuff' => 'things');
print_r($array);
//prints - Array ( [stuff] => things )
$arrayEncoded = json_encode($array);
echo $arrayEncoded . "<br />";
//prints - {"stuff":"things"}
$arrayDecoded = json_decode($arrayEncoded);
print_r($arrayDecoded);
//prints - stdClass Object ( [stuff] => things )

Why does PHP make a class out of a JSON Object?

Shouldn’t a json encoded and json decoded array produce the EXACT same result?

Asked by Derek Adair

Solution #1

At https://secure.php.net/json decode, look at the second parameter of json decode($json, $assoc, $depth).

Answered by VolkerK

Solution #2

$arrayDecoded = json_decode($arrayEncoded, true);

gives you an array.

Answered by Kai Chan

Solution #3

Take a closer look at the encoded JSON output; I’ve expanded on the sample provided by the OP:

$array = array(
    'stuff' => 'things',
    'things' => array(
        'controller', 'playing card', 'newspaper', 'sand paper', 'monitor', 'tree'
    )
);
$arrayEncoded = json_encode($array);
echo $arrayEncoded;
//prints - {"stuff":"things","things":["controller","playing card","newspaper","sand paper","monitor","tree"]}

The JSON format was derived from the same standard as JavaScript (ECMAScript Programming Language Standard) and if you would look at the format it looks like JavaScript. It is a JSON object ({} = object) having a property “stuff” with value “things” and has a property “things” with it’s value being an array of strings ([] = array).

JSON (as JavaScript) doesn’t know associative arrays only indexed arrays. So when JSON encoding a PHP associative array, this will result in a JSON string containing this array as an “object”.

json decode($arrayEncoded) is now used to decode the JSON once more. Because the decode function has no idea where this JSON string came from (a PHP array), it decodes it into an unknown object, which in PHP is stdClass. The “things” array of strings WILL decode into an indexed PHP array, as you can see.

Also see:

The ‘items’ came from https://www.randomlists.com/things.

Answered by 7ochem

Solution #4

Although, as mentioned, you could add a second parameter here to indicate you want an array returned:

$array = json_decode($json, true);

Many people would rather cast the outcomes as follows:

$array = (array)json_decode($json);

It could be easier to read.

Answered by Andrew

Solution #5

tl;dr: Associative arrays are not supported by JavaScript, and thus by JSON.

It’s JSON, not JSAAN, after all.

In order to encode into JSON, PHP must turn your array into an object.

Answered by LaVache

Post is based on https://stackoverflow.com/questions/2281973/json-encode-json-decode-returns-stdclass-instead-of-array-in-php