note 100810 added to function.json-encode
| From: | boukeversteegh at gmail dot com | Date: | Mon, 08 Nov 2010 17:23:09 +0000 |
| Subject: | note 100810 added to function.json-encode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-173859@lists.php.net to get a copy of this message | ||
For users of php 5.1.6 or lower, a native json_encode function. This version handles objects, and
makes proper distinction between [lists] and {associative arrays}, mixed arrays work as well. It can
handle newlines and quotes in both keys and data.
This function does _not_ convert non-ascii symbols to "\uXXXX" format as does json_encode.
Besides that, it gives the exact same output as json_encode.
<?php
function __json_encode( $data ) {
if( is_array($data) || is_object($data) ) {
# See php.net / is_array
$is_assoc =
(is_array($data) &&
0 !== count(array_diff_key($data, array_keys(array_keys($data)))));
if( $is_assoc || is_object($data) ) {
$items = Array();
foreach( $data as $key => $value ) {
$items[] = __json_encode("$key") . ':' . __json_encode($value);
}
$json = '{' . implode(',', $items) . '}';
} else {
$json = '[' . implode(',', array_map('__json_encode', $data) ) .
']';
}
} elseif( is_int($data) || is_float($data) ) {
$json = strtolower($data); # like 10e99
} elseif( null === $data ) {
$json = 'null';
} else {
$json = '"' . addcslashes($data, "\"\\\n\r") . '"';
# String
}
return $json;
}
?>
Example:
<?php
$data = new StdClass();
$data->foo = "bar";
$data->dict = Array('1' => 1, '2' => 2, '3' =>
'three', 'four');
$data->list = Array('one','two','three','',null,new
StdClass(),Array(),10e99);
json_encode($data) === __json_encode($data); // true
----
Server IP: 91.199.167.223
Probable Submitter: 192.87.139.139
----
Manual Page -- http://www.php.net/manual/en/function.json-encode.php
Edit -- https://master.php.net/note/edit/100810
Del: integrated -- https://master.php.net/note/delete/100810/integrated
Del: useless -- https://master.php.net/note/delete/100810/useless
Del: bad code -- https://master.php.net/note/delete/100810/bad+code
Del: spam -- https://master.php.net/note/delete/100810/spam
Del: non-english -- https://master.php.net/note/delete/100810/non-english
Del: in docs -- https://master.php.net/note/delete/100810/in+docs
Del: other reasons-- https://master.php.net/note/delete/100810
Reject -- https://master.php.net/note/reject/100810
Search -- https://master.php.net/manage/user-notes.php