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 an array that is json_encoded then json_decoded yield 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);

provides you with 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 is based on the same standard as JavaScript (ECMAScript Programming Language Standard), and therefore looks quite similar to JavaScript. It’s a JSON object ( = object) with two properties: “stuff” with the value “things” and “things” with the value “an array of strings” ([] = array).

JSON (like JavaScript) only understands indexed arrays, not associative arrays. When a PHP associative array is JSON encoded, the result is a JSON string that contains the array as a “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 previously indicated, a second parameter could be used to indicate that 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