#11963 closed enhancement (fixed)
json_decode() only supports only "stdClass Object" but no "array"
Reported by: |
|
Owned by: | |
---|---|---|---|
Milestone: | 3.0 | Priority: | normal |
Severity: | normal | Version: | 2.9.1 |
Component: | General | Keywords: | needs-patch |
Focuses: | Cc: |
Description
Hi,
to allow the json_decode() function to return "array" instead of "stdClass Object", normally the second argument to json_decode() is set to TRUE. Wordpress at least 2.9.1 only supports one argument.
So perhaps it may be useful to change the wp-includes/compat.php with the following:
--- compat.php 2010-01-20 23:42:32.000000000 +0100 +++ compat.php.new 2010-01-20 23:30:18.000000000 +0100 @@ -138,12 +138,19 @@ } if ( !function_exists('json_decode') ) { - function json_decode( $string ) { + function json_decode( $string, $bool ) { global $wp_json; if ( !is_a($wp_json, 'Services_JSON') ) { require_once( 'class-json.php' ); - $wp_json = new Services_JSON(); + if ($bool == TRUE) { + // use associative array + $wp_json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE); + } + else { + // use stdClass object + $wp_json = new Services_JSON(); + } } return $wp_json->decode( $string );
Greetings, Michael
Change History (7)
#2
@
15 years ago
Hi nacin,
you are right, i didn't consider the one-time initialisation. Perhaps a conversion like this could be a solution:
function ObjToArr($data) { if (is_object($data)) $data = get_object_vars($data); return is_array($data) ? array_map(__FUNCTION__, $data) : $data; } if ( !function_exists('json_decode') ) { function json_decode( $string, $bool ) { global $wp_json; if ( !is_a($wp_json, 'Services_JSON') ) { require_once( 'class-json.php' ); $wp_json = new Services_JSON(); } if ($bool === TRUE) { return ObjToArr($wp_json->decode( $string )); } else { return $wp_json->decode( $string ); } } }
Greetings Michael
#3
@
15 years ago
- Component changed from Optimization to General
- Type changed from enhancement to feature request
#5
@
15 years ago
- Keywords needs-patch added; json_decode array removed
- Milestone changed from Unassigned to 3.0
Since we introduced json_decode() for pre-PHP 5.2 compat, we should probably implement it with the array option.
Setting to 3.0 for now. Needs patch or it will get punted quick.
Note: See
TracTickets for help on using
tickets.
The compat version of
json_decode()
is designed to only initialize theServices_JSON()
class once, even if called multiple times. Using the diff you suggest, if you used bothjson_decode( $json, true )
andjson_decode( $json, false )
in a script, whichever was called first would be what you would get for both.There are two ways to do this if we wish to support this level of compatibility. We could allow
Services_JSON()
to be initialized a second time using the loose typing option if an array is requested... or, potentially less overhead, convert the result of$wp_json->decode()
if arrays are what is requested.