3 * Minimal JSON generator for FusionForge
6 * Thorsten “mirabilos” Glaser <t.glaser@tarent.de>
9 * This file is part of FusionForge. FusionForge is free software;
10 * you can redistribute it and/or modify it under the terms of the
11 * GNU General Public License as published by the Free Software
12 * Foundation; either version 2 of the License, or (at your option)
15 * FusionForge is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with FusionForge; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * Do *not* use PHP’s json_encode because it is broken. Rather,
25 * use (and, if necessary, extend) this module.
29 * Encodes an array (indexed or associative) as JSON.
34 function minijson_encode($x, $ri="") {
35 if (!isset($x) || is_null($x) || (is_float($x) &&
36 (is_nan($x) || is_infinite($x))))
51 foreach (str_split($x) as $v) {
57 } else if ($y == 10) {
59 } else if ($y == 12) {
61 } else if ($y == 13) {
63 } else if ($y < 0x20 || ($y > 0x7E && $y < 0xA0)) {
64 $rs .= sprintf("\\u%04X", $y);
65 } else if ($y > 0xFFFD) {
66 /* XXX encode as UTF-16 */
68 } else if ($v == "\"" || $v == "\\") {
94 /* all array keys are integers */
96 sort($s, SORT_NUMERIC);
97 /* test keys for order and delta */
110 /* all array keys are integers 0‥n */
118 minijson_encode($x[$v], $ri." ");
120 return $rs."\n".$ri."]";
129 $rs .= $ri . " " . minijson_encode((string)$v) .
130 ": " . minijson_encode($x[$v], $ri." ");
132 return $rs."\n".$ri."}";
135 /* treat everything else as array or string */
137 return minijson_encode((array)$x, $ri);
138 return minijson_encode((string)$x, $ri);