2 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4 * Converts to and from JSON format.
6 * JSON (JavaScript Object Notation) is a lightweight data-interchange
7 * format. It is easy for humans to read and write. It is easy for machines
8 * to parse and generate. It is based on a subset of the JavaScript
9 * Programming Language, Standard ECMA-262 3rd Edition - December 1999.
10 * This feature can also be found in Python. JSON is a text format that is
11 * completely language independent but uses conventions that are familiar
12 * to programmers of the C-family of languages, including C, C++, C#, Java,
13 * JavaScript, Perl, TCL, and many others. These properties make JSON an
14 * ideal data-interchange language.
16 * This package provides a simple encoder and decoder for JSON notation. It
17 * is intended for use with client-side Javascript applications that make
18 * use of HTTPRequest to perform server communication functions - data can
19 * be encoded into JSON notation for use in a client-side javascript, or
20 * decoded from incoming Javascript requests. JSON format is native to
21 * Javascript, and can be directly eval()'ed with no further parsing
24 * All strings should be in ASCII or UTF-8 format!
26 * LICENSE: Redistribution and use in source and binary forms, with or
27 * without modification, are permitted provided that the following
28 * conditions are met: Redistributions of source code must retain the
29 * above copyright notice, this list of conditions and the following
30 * disclaimer. Redistributions in binary form must reproduce the above
31 * copyright notice, this list of conditions and the following disclaimer
32 * in the documentation and/or other materials provided with the
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
37 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
38 * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
39 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
40 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
41 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
42 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
43 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
44 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
48 * @package Services_JSON
49 * @author Michal Migurski <mike-json@teczno.com>
50 * @author Matt Knapp <mdknapp[at]gmail[dot]com>
51 * @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
52 * @copyright 2005 Michal Migurski
53 * @version CVS: $Id: JSON.php 307804 2011-01-28 00:16:42Z alan_k $
54 * @license http://www.opensource.org/licenses/bsd-license.php
55 * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
59 * Marker constant for Services_JSON::decode(), used to flag stack state
61 define('SERVICES_JSON_SLICE', 1);
64 * Marker constant for Services_JSON::decode(), used to flag stack state
66 define('SERVICES_JSON_IN_STR', 2);
69 * Marker constant for Services_JSON::decode(), used to flag stack state
71 define('SERVICES_JSON_IN_ARR', 3);
74 * Marker constant for Services_JSON::decode(), used to flag stack state
76 define('SERVICES_JSON_IN_OBJ', 4);
79 * Marker constant for Services_JSON::decode(), used to flag stack state
81 define('SERVICES_JSON_IN_CMT', 5);
84 * Behavior switch for Services_JSON::decode()
86 define('SERVICES_JSON_LOOSE_TYPE', 16);
89 * Behavior switch for Services_JSON::decode()
91 define('SERVICES_JSON_SUPPRESS_ERRORS', 32);
94 * Behavior switch for Services_JSON::decode()
96 define('SERVICES_JSON_USE_TO_JSON', 64);
99 * Converts to and from JSON format.
101 * Brief example of use:
104 * // create a new instance of Services_JSON
105 * $json = new Services_JSON();
107 * // convert a complexe value to JSON notation, and send it to the browser
108 * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
109 * $output = $json->encode($value);
112 * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
114 * // accept incoming POST data, assumed to be in JSON notation
115 * $input = file_get_contents('php://input', 1000000);
116 * $value = $json->decode($input);
122 * constructs a new JSON instance
124 * @param int $use object behavior flags; combine with boolean-OR
127 * - SERVICES_JSON_LOOSE_TYPE: loose typing.
128 * "{...}" syntax creates associative arrays
129 * instead of objects in decode().
130 * - SERVICES_JSON_SUPPRESS_ERRORS: error suppression.
131 * Values which can't be encoded (e.g. resources)
132 * appear as NULL instead of throwing errors.
133 * By default, a deeply-nested resource will
134 * bubble up with an error, so all return values
135 * from encode() should be checked with isError()
136 * - SERVICES_JSON_USE_TO_JSON: call toJSON when serializing objects
137 * It serializes the return value from the toJSON call rather
138 * than the object it'self, toJSON can return associative arrays,
139 * strings or numbers, if you return an object, make sure it does
140 * not have a toJSON method, otherwise an error will occur.
142 function __construct($use = 0)
145 $this->_mb_strlen = function_exists('mb_strlen');
146 $this->_mb_convert_encoding = function_exists('mb_convert_encoding');
147 $this->_mb_substr = function_exists('mb_substr');
149 // private - cache the mbstring lookup results..
150 var $_mb_strlen = false;
151 var $_mb_substr = false;
152 var $_mb_convert_encoding = false;
154 // tab and crlf are used by stringfy to produce pretty JSON.
159 * convert a string from one UTF-16 char to one UTF-8 char
161 * Normally should be handled by mb_convert_encoding, but
162 * provides a slower PHP-only method for installations
163 * that lack the multibye string extension.
165 * @param string $utf16 UTF-16 character
166 * @return string UTF-8 character
169 function utf162utf8($utf16)
171 // oh please oh please oh please oh please oh please
172 if($this->_mb_convert_encoding) {
173 return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
176 $bytes = (ord($utf16[0]) << 8) | ord($utf16[1]);
179 case ((0x7F & $bytes) == $bytes):
180 // this case should never be reached, because we are in ASCII range
181 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
182 return chr(0x7F & $bytes);
184 case (0x07FF & $bytes) == $bytes:
185 // return a 2-byte UTF-8 character
186 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
187 return chr(0xC0 | (($bytes >> 6) & 0x1F))
188 . chr(0x80 | ($bytes & 0x3F));
190 case (0xFFFF & $bytes) == $bytes:
191 // return a 3-byte UTF-8 character
192 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
193 return chr(0xE0 | (($bytes >> 12) & 0x0F))
194 . chr(0x80 | (($bytes >> 6) & 0x3F))
195 . chr(0x80 | ($bytes & 0x3F));
198 // ignoring UTF-32 for now, sorry
203 * convert a string from one UTF-8 char to one UTF-16 char
205 * Normally should be handled by mb_convert_encoding, but
206 * provides a slower PHP-only method for installations
207 * that lack the multibye string extension.
209 * @param string $utf8 UTF-8 character
210 * @return string UTF-16 character
213 function utf82utf16($utf8)
215 // oh please oh please oh please oh please oh please
216 if($this->_mb_convert_encoding) {
217 return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
220 switch($this->strlen8($utf8)) {
222 // this case should never be reached, because we are in ASCII range
223 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
227 // return a UTF-16 character from a 2-byte UTF-8 char
228 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
229 return chr(0x07 & (ord($utf8[0]) >> 2))
230 . chr((0xC0 & (ord($utf8[0]) << 6))
231 | (0x3F & ord($utf8[1])));
234 // return a UTF-16 character from a 3-byte UTF-8 char
235 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
236 return chr((0xF0 & (ord($utf8[0]) << 4))
237 | (0x0F & (ord($utf8[1]) >> 2)))
238 . chr((0xC0 & (ord($utf8[1]) << 6))
239 | (0x7F & ord($utf8[2])));
242 // ignoring UTF-32 for now, sorry
248 * stringfy an arbitrary variable into JSON format (and sends JSON Header)
249 * UNSAFE - does not send HTTP headers (to be compatible with Javsacript Spec)
251 * @param mixed $var any number, boolean, string, array, or object to be encoded.
252 * see argument 1 to Services_JSON() above for array-parsing behavior.
253 * if var is a strng, note that encode() always expects it
254 * to be in ASCII or UTF-8 format!
255 * @param mixed $replacer NOT SUPPORTED YET.
256 * @param number|string $space
257 * an optional parameter that specifies the indentation
258 * of nested structures. If it is omitted, the text will
259 * be packed without extra whitespace. If it is a number,
260 * it will specify the number of spaces to indent at each
261 * level. If it is a string (such as '\t' or ' '),
262 * it contains the characters used to indent at each level.
264 * @return mixed JSON string representation of input var or an error if a problem occurs
267 static function stringify($var, $replacer=false, $space=false)
269 //header('Content-type: application/json');
270 $s = new Services_JSON(SERVICES_JSON_USE_TO_JSON);
272 $s->_tab = is_numeric($space) ? str_repeat(' ', $space) : $space;
275 return $s->encodeUnsafe($var);
279 * encodes an arbitrary variable into JSON format (and sends JSON Header)
281 * @param mixed $var any number, boolean, string, array, or object to be encoded.
282 * see argument 1 to Services_JSON() above for array-parsing behavior.
283 * if var is a strng, note that encode() always expects it
284 * to be in ASCII or UTF-8 format!
286 * @return mixed JSON string representation of input var or an error if a problem occurs
289 function encode($var)
291 header('Content-type: text/javascript'); // changed to make debugging easier.
292 return $this->encodeUnsafe($var);
295 * encodes an arbitrary variable into JSON format without JSON Header - warning - may allow XSS!!!!)
297 * @param mixed $var any number, boolean, string, array, or object to be encoded.
298 * see argument 1 to Services_JSON() above for array-parsing behavior.
299 * if var is a strng, note that encode() always expects it
300 * to be in ASCII or UTF-8 format!
302 * @return mixed JSON string representation of input var or an error if a problem occurs
305 function encodeUnsafe($var)
307 // see bug #16908 - regarding numeric locale printing
308 $lc = setlocale(LC_NUMERIC, 0);
309 setlocale(LC_NUMERIC, 'C');
310 $ret = $this->_encode($var);
311 setlocale(LC_NUMERIC, $lc);
316 * PRIVATE CODE that does the work of encodes an arbitrary variable into JSON format
318 * @param mixed $var any number, boolean, string, array, or object to be encoded.
319 * see argument 1 to Services_JSON() above for array-parsing behavior.
320 * if var is a strng, note that encode() always expects it
321 * to be in ASCII or UTF-8 format!
323 * @return mixed JSON string representation of input var or an error if a problem occurs
326 function _encode($var)
328 $ind = str_repeat($this->_tab, $this->_indent);
329 $indx = $ind . $this->_tab;
331 switch (gettype($var)) {
333 return $var ? 'true' : 'false';
346 // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
348 $strlen_var = $this->strlen8($var);
351 * Iterate over every character in the string,
352 * escaping with a slash or encoding to UTF-8 where necessary
354 for ($c = 0; $c < $strlen_var; ++$c) {
356 $ord_var_c = ord($var[$c]);
359 case $ord_var_c == 0x08:
362 case $ord_var_c == 0x09:
365 case $ord_var_c == 0x0A:
368 case $ord_var_c == 0x0C:
371 case $ord_var_c == 0x0D:
375 case $ord_var_c == 0x22:
376 case $ord_var_c == 0x2F:
377 case $ord_var_c == 0x5C:
378 // double quote, slash, slosh
379 $ascii .= '\\'.$var[$c];
382 case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
383 // characters U-00000000 - U-0000007F (same as ASCII)
387 case (($ord_var_c & 0xE0) == 0xC0):
388 // characters U-00000080 - U-000007FF, mask 110XXXXX
389 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
390 if ($c+1 >= $strlen_var) {
396 $char = pack('C*', $ord_var_c, ord($var[$c + 1]));
398 $utf16 = $this->utf82utf16($char);
399 $ascii .= sprintf('\u%04s', bin2hex($utf16));
402 case (($ord_var_c & 0xF0) == 0xE0):
403 if ($c+2 >= $strlen_var) {
408 // characters U-00000800 - U-0000FFFF, mask 1110XXXX
409 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
410 $char = pack('C*', $ord_var_c,
414 $utf16 = $this->utf82utf16($char);
415 $ascii .= sprintf('\u%04s', bin2hex($utf16));
418 case (($ord_var_c & 0xF8) == 0xF0):
419 if ($c+3 >= $strlen_var) {
424 // characters U-00010000 - U-001FFFFF, mask 11110XXX
425 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
426 $char = pack('C*', $ord_var_c,
431 $utf16 = $this->utf82utf16($char);
432 $ascii .= sprintf('\u%04s', bin2hex($utf16));
435 case (($ord_var_c & 0xFC) == 0xF8):
436 // characters U-00200000 - U-03FFFFFF, mask 111110XX
437 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
438 if ($c+4 >= $strlen_var) {
443 $char = pack('C*', $ord_var_c,
449 $utf16 = $this->utf82utf16($char);
450 $ascii .= sprintf('\u%04s', bin2hex($utf16));
453 case (($ord_var_c & 0xFE) == 0xFC):
454 if ($c+5 >= $strlen_var) {
459 // characters U-04000000 - U-7FFFFFFF, mask 1111110X
460 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
461 $char = pack('C*', $ord_var_c,
468 $utf16 = $this->utf82utf16($char);
469 $ascii .= sprintf('\u%04s', bin2hex($utf16));
473 return '"'.$ascii.'"';
477 * As per JSON spec if any array key is not an integer
478 * we must treat the the whole array as an object. We
479 * also try to catch a sparsely populated associative
480 * array with numeric keys here because some JS engines
481 * will create an array with empty indexes up to
482 * max_index which can cause memory issues and because
483 * the keys, which may be relevant, will be remapped
486 * As per the ECMA and JSON specification an object may
487 * have any string as a property. Unfortunately due to
488 * a hole in the ECMA specification if the key is a
489 * ECMA reserved word or starts with a digit the
490 * parameter is only accessible using ECMAScript's
494 // treat as a JSON object
495 if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
497 $properties = array_map(array($this, 'name_value'),
501 foreach($properties as $property) {
502 if(Services_JSON::isError($property)) {
507 return "{" . $this->_crlf . $indx .
508 join(",". $this->_crlf . $indx, $properties) . $this->_crlf .
513 // treat it like a regular array
515 $elements = array_map(array($this, '_encode'), $var);
518 foreach($elements as $element) {
519 if(Services_JSON::isError($element)) {
524 $pad = $this->_tab === '' ? '' : ' ';
526 // short array, just show it on one line.
527 if (strlen(join(',' . $pad, $elements)) < 30) {
528 return '[' . join(',' . $pad, $elements) . ']';
531 return "[" . $this->_crlf .
532 $indx . join(",". $this->_crlf . $indx, $elements) . $this->_crlf .
537 // support toJSON methods.
538 if (($this->use & SERVICES_JSON_USE_TO_JSON) && method_exists($var, 'toJSON')) {
539 // this may end up allowing unlimited recursion
540 // so we check the return value to make sure it's not got the same method.
541 $recode = $var->toJSON();
543 if (method_exists($recode, 'toJSON')) {
545 return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
547 : new Services_JSON_Error(get_class($var).
548 " toJSON returned an object with a toJSON method.");
552 return $this->_encode( $recode );
555 $vars = get_object_vars($var);
558 $properties = array_map(array($this, 'name_value'),
560 array_values($vars));
563 foreach($properties as $property) {
564 if(Services_JSON::isError($property)) {
569 return "{" . $this->_crlf .
570 $indx . join(",". $this->_crlf . $indx, $properties) . $this->_crlf .
574 return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
576 : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
581 * array-walking function for use in generating JSON-formatted name-value pairs
583 * @param string $name name of key to use
584 * @param mixed $value reference to an array element to be encoded
586 * @return string JSON-formatted name-value pair, like '"name":value'
589 function name_value($name, $value)
591 $encoded_value = $this->_encode($value);
593 if(Services_JSON::isError($encoded_value)) {
594 return $encoded_value;
597 $pad = $this->_tab === '' ? '' : ' ';
599 return $this->_encode(strval($name)) . $pad . ':' . $pad . $encoded_value;
603 * reduce a string by removing leading and trailing comments and whitespace
605 * @param $str string string value to strip of comments and whitespace
607 * @return string string value stripped of comments and whitespace
610 function reduce_string($str)
612 $str = preg_replace(array(
614 // eliminate single line comments in '// ...' form
617 // eliminate multi-line comments in '/* ... */' form, at start of string
618 '#^\s*/\*(.+)\*/#Us',
620 // eliminate multi-line comments in '/* ... */' form, at end of string
625 // eliminate extraneous space
630 * decodes a JSON string into appropriate variable
632 * @param string $str JSON-formatted string
634 * @return mixed number, boolean, string, array, or object
635 * corresponding to given JSON input string.
636 * See argument 1 to Services_JSON() above for object-output behavior.
637 * Note that decode() always returns strings
638 * in ASCII or UTF-8 format!
641 function decode($str)
643 $str = $this->reduce_string($str);
645 switch (strtolower($str)) {
658 if (is_numeric($str)) {
659 // Lookie-loo, it's a number
661 // This would work on its own, but I'm trying to be
662 // good about returning integers where appropriate:
663 // return (float)$str;
665 // Return float or int, as appropriate
666 return ((float)$str == (integer)$str)
670 } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) {
671 // STRINGS RETURNED IN UTF-8 FORMAT
672 $delim = $this->substr8($str, 0, 1);
673 $chrs = $this->substr8($str, 1, -1);
675 $strlen_chrs = $this->strlen8($chrs);
677 for ($c = 0; $c < $strlen_chrs; ++$c) {
679 $substr_chrs_c_2 = $this->substr8($chrs, $c, 2);
680 $ord_chrs_c = ord($chrs[$c]);
683 case $substr_chrs_c_2 == '\b':
687 case $substr_chrs_c_2 == '\t':
691 case $substr_chrs_c_2 == '\n':
695 case $substr_chrs_c_2 == '\f':
699 case $substr_chrs_c_2 == '\r':
704 case $substr_chrs_c_2 == '\\"':
705 case $substr_chrs_c_2 == '\\\'':
706 case $substr_chrs_c_2 == '\\\\':
707 case $substr_chrs_c_2 == '\\/':
708 if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
709 ($delim == "'" && $substr_chrs_c_2 != '\\"')) {
710 $utf8 .= $chrs[++$c];
714 case preg_match('/\\\u[0-9A-F]{4}/i', $this->substr8($chrs, $c, 6)):
715 // single, escaped unicode character
716 $utf16 = chr(hexdec($this->substr8($chrs, ($c + 2), 2)))
717 . chr(hexdec($this->substr8($chrs, ($c + 4), 2)));
718 $utf8 .= $this->utf162utf8($utf16);
722 case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
726 case ($ord_chrs_c & 0xE0) == 0xC0:
727 // characters U-00000080 - U-000007FF, mask 110XXXXX
728 //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
729 $utf8 .= $this->substr8($chrs, $c, 2);
733 case ($ord_chrs_c & 0xF0) == 0xE0:
734 // characters U-00000800 - U-0000FFFF, mask 1110XXXX
735 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
736 $utf8 .= $this->substr8($chrs, $c, 3);
740 case ($ord_chrs_c & 0xF8) == 0xF0:
741 // characters U-00010000 - U-001FFFFF, mask 11110XXX
742 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
743 $utf8 .= $this->substr8($chrs, $c, 4);
747 case ($ord_chrs_c & 0xFC) == 0xF8:
748 // characters U-00200000 - U-03FFFFFF, mask 111110XX
749 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
750 $utf8 .= $this->substr8($chrs, $c, 5);
754 case ($ord_chrs_c & 0xFE) == 0xFC:
755 // characters U-04000000 - U-7FFFFFFF, mask 1111110X
756 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
757 $utf8 .= $this->substr8($chrs, $c, 6);
767 } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
768 // array, or object notation
770 if ($str[0] == '[') {
771 $stk = array(SERVICES_JSON_IN_ARR);
774 if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
775 $stk = array(SERVICES_JSON_IN_OBJ);
778 $stk = array(SERVICES_JSON_IN_OBJ);
779 $obj = new stdClass();
783 array_push($stk, array('what' => SERVICES_JSON_SLICE,
787 $chrs = $this->substr8($str, 1, -1);
788 $chrs = $this->reduce_string($chrs);
791 if (reset($stk) == SERVICES_JSON_IN_ARR) {
800 //print("\nparsing {$chrs}\n");
802 $strlen_chrs = $this->strlen8($chrs);
804 for ($c = 0; $c <= $strlen_chrs; ++$c) {
807 $substr_chrs_c_2 = $this->substr8($chrs, $c, 2);
809 if (($c == $strlen_chrs) || (($chrs[$c] == ',') && ($top['what'] == SERVICES_JSON_SLICE))) {
810 // found a comma that is not inside a string, array, etc.,
811 // OR we've reached the end of the character list
812 $slice = $this->substr8($chrs, $top['where'], ($c - $top['where']));
813 array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
814 //print("Found split at [$c]: ".$this->substr8($chrs, $top['where'], (1 + $c - $top['where']))."\n");
816 if (reset($stk) == SERVICES_JSON_IN_ARR) {
817 // we are in an array, so just push an element onto the stack
818 array_push($arr, $this->decode($slice));
820 } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
821 // we are in an object, so figure
822 // out the property name and set an
823 // element in an associative array,
827 if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:/Uis', $slice, $parts)) {
829 $key = $this->decode($parts[1]);
830 $val = $this->decode(trim(substr($slice, strlen($parts[0])), ", \t\n\r\0\x0B"));
831 if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
836 } elseif (preg_match('/^\s*(\w+)\s*:/Uis', $slice, $parts)) {
837 // name:value pair, where name is unquoted
839 $val = $this->decode(trim(substr($slice, strlen($parts[0])), ", \t\n\r\0\x0B"));
841 if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
850 } elseif ((($chrs[$c] == '"') || ($chrs[$c] == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) {
851 // found a quote, and we are not inside a string
852 array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs[$c]));
853 //print("Found start of string at [$c]\n");
855 } elseif (($chrs[$c] == $top['delim']) &&
856 ($top['what'] == SERVICES_JSON_IN_STR) &&
857 (($this->strlen8($this->substr8($chrs, 0, $c)) - $this->strlen8(rtrim($this->substr8($chrs, 0, $c), '\\'))) % 2 != 1)) {
858 // found a quote, we're in a string, and it's not escaped
859 // we know that it's not escaped becase there is _not_ an
860 // odd number of backslashes at the end of the string so far
862 //print("Found end of string at [$c]: ".$this->substr8($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
864 } elseif (($chrs[$c] == '[') &&
865 in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
866 // found a left-bracket, and we are in an array, object, or slice
867 array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false));
868 //print("Found start of array at [$c]\n");
870 } elseif (($chrs[$c] == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) {
871 // found a right-bracket, and we're in an array
873 //print("Found end of array at [$c]: ".$this->substr8($chrs, $top['where'], (1 + $c - $top['where']))."\n");
875 } elseif (($chrs[$c] == '{') &&
876 in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
877 // found a left-brace, and we are in an array, object, or slice
878 array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false));
879 //print("Found start of object at [$c]\n");
881 } elseif (($chrs[$c] == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) {
882 // found a right-brace, and we're in an object
884 //print("Found end of object at [$c]: ".$this->substr8($chrs, $top['where'], (1 + $c - $top['where']))."\n");
886 } elseif (($substr_chrs_c_2 == '/*') &&
887 in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
888 // found a comment start, and we are in an array, object, or slice
889 array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false));
891 //print("Found start of comment at [$c]\n");
893 } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) {
894 // found a comment end, and we're in one now
898 for ($i = $top['where']; $i <= $c; ++$i)
899 $chrs = substr_replace($chrs, ' ', $i, 1);
901 //print("Found end of comment at [$c]: ".$this->substr8($chrs, $top['where'], (1 + $c - $top['where']))."\n");
907 if (reset($stk) == SERVICES_JSON_IN_ARR) {
910 } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
920 * @todo Ultimately, this should just call PEAR::isError()
922 function isError($data, $code = null)
924 if (class_exists('pear')) {
925 return PEAR::isError($data, $code);
926 } elseif (is_object($data) && (get_class($data) == 'services_json_error' ||
927 is_subclass_of($data, 'services_json_error'))) {
935 * Calculates length of string in bytes
937 * @return integer length
939 function strlen8( $str )
941 if ( $this->_mb_strlen ) {
942 return mb_strlen( $str, "8bit" );
944 return strlen( $str );
948 * Returns part of a string, interpreting $start and $length as number of bytes.
950 * @param integer start
951 * @param integer length
952 * @return integer length
954 function substr8( $string, $start, $length=false )
956 if ( $length === false ) {
957 $length = $this->strlen8( $string ) - $start;
959 if ( $this->_mb_substr ) {
960 return mb_substr( $string, $start, $length, "8bit" );
962 return substr( $string, $start, $length );
967 if (class_exists('PEAR_Error')) {
969 class Services_JSON_Error extends PEAR_Error
971 function __construct($message = 'unknown error', $code = null,
972 $mode = null, $options = null, $userinfo = null)
974 parent::__construct($message, $code, $mode, $options, $userinfo);
981 * @todo Ultimately, this class shall be descended from PEAR_Error
983 class Services_JSON_Error
985 function __construct($message = 'unknown error', $code = null,
986 $mode = null, $options = null, $userinfo = null)