How to get json_decode or Services_JSON to return associative arrays

json_decode takes a JSON (JavaScript Object Notation) encoded string and converts it into a PHP variable. (More information on PHP documentation.)

[code lang=”php”][/code]

The above code would result in the following:

[code lang=”php”]object(stdClass)#1 (5) {
[“a”] => int(1)
[“b”] => int(2)
[“c”] => int(3)
[“d”] => int(4)
[“e”] => int(5)
}

array(5) {
[“a”] => int(1)
[“b”] => int(2)
[“c”] => int(3)
[“d”] => int(4)
[“e”] => int(5)
}
[/code]

When TRUE, returned objects will be converted into associative arrays. PHP’s associative arrays are amongst the easiest to use so i generally prefer an array to be returned.

When working on older PHP configurations such as in PHP 5.1, json_decode is not available. I use Michal Migurski’s Service_JSON. You can get the source code here.

The following does a json decode using the Services_JSON class.

[code lang=”php”]decode($json_text);
?>[/code]

If you use Services_JSON() instead, you are returned with StdClass. Using new Services_JSON (SERVICES_JSON_LOOSE_TYPE) returns you an array instead.

1 thought on “How to get json_decode or Services_JSON to return associative arrays”

Leave a Reply

Your email address will not be published. Required fields are marked *