| | 4207 | |
| | 4208 | /** |
| | 4209 | * A Json encoder which supports associative arrays as well as objects |
| | 4210 | */ |
| | 4211 | function wp_json_encode( $data ) { |
| | 4212 | wp_json_encode__add_object_prop( $data ); |
| | 4213 | return json_encode( $data ); |
| | 4214 | } |
| | 4215 | function wp_json_encode__add_object_prop( &$data ) { |
| | 4216 | if ( is_object( $data ) ) { |
| | 4217 | // Convert before adding prop to avoid modifying the original object |
| | 4218 | $data = (array) $data; |
| | 4219 | $data['_object'] = 1; |
| | 4220 | } |
| | 4221 | if ( is_array( $data ) ) |
| | 4222 | array_walk( $data, 'wp_json_encode__add_object_prop' ); |
| | 4223 | } |
| | 4224 | |
| | 4225 | function wp_json_decode( $data ) { |
| | 4226 | $data = json_decode( $data, true ); |
| | 4227 | wp_json_decode__convert_objects( $data ); |
| | 4228 | return $data; |
| | 4229 | } |
| | 4230 | function wp_json_decode__convert_objects( &$data ) { |
| | 4231 | if ( ! is_array( $data ) ) |
| | 4232 | return; |
| | 4233 | |
| | 4234 | array_walk( $data, 'wp_json_decode__convert_objects' ); |
| | 4235 | |
| | 4236 | if ( ! isset( $data['_object'] ) && 1 === $data['_object'] ) { |
| | 4237 | unset( $data['_object'] ); |
| | 4238 | $data = (object) $data; |
| | 4239 | } |
| | 4240 | } |
| | 4241 | |
| | 4242 | function wp_json_test() { |
| | 4243 | $data = (object) array( |
| | 4244 | 'objects' => array( |
| | 4245 | (object) array( 'object1' => 1 ), |
| | 4246 | (object) array( 'object2' => 2, 'props' => array( 1,2,3 ) ) |
| | 4247 | ), |
| | 4248 | 'arrays' => array( |
| | 4249 | array(1,2,3,4) |
| | 4250 | ), |
| | 4251 | 'int' => 1, |
| | 4252 | 'bool' => true, |
| | 4253 | ); |
| | 4254 | |
| | 4255 | $encoded = wp_json_encode( $data ); |
| | 4256 | $decoded = wp_json_decode( $encoded ); |
| | 4257 | echo '<pre>'; |
| | 4258 | print_r( $decoded == $data ); |
| | 4259 | print_r( compact( 'encoded', 'decoded', 'data' ) ); |
| | 4260 | echo '</pre>'; |
| | 4261 | } |
| | 4262 | No newline at end of file |