Apr 28

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.)

<?php
$json_text = ‘{"a":1,"b":2,"c":3,"d":4,"e":5}’;
var_dump(json_decode($json_text));
var_dump(json_decode($json_text, true));
?>

The above code would result in the following:

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)
}

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.

<?php
require_once ‘JSON.php’;
$json_text = ‘{"a":1,"b":2,"c":3,"d":4,"e":5}’;
$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
$array = $json->decode($json_text);
?>

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

Possibly related:

  1. jQuery’s getJSON failing randomly in Internet Explorer
  2. List of stop words
  3. CakePHP’s built-in Pages Controller
  4. How to perform routing in CakePHP 1.2

No comments yet. Leave yours here.


WordPress powered and Django inspired.
Love and elephants come after.
RSS: Posts and comments.