note 82903 added to function.json-encode

From: Date: Thu, 01 May 2008 00:34:05 +0000
Subject: note 82903 added to function.json-encode
Groups: php.notes 
Request: Send a blank email to php-notes+get-138953@lists.php.net to get a copy of this message
I've modified jjoss' php2js function to remove the extra whitespace (not needed for machine-readable output) and leave quotes off of non-string variables so that it more closely resembles the output of json_encode. In my testing this function and json_encode return the exact same result. I use this as a substitute if json_encode is not defined, so if anyone finds any differences between this and json_encode I would like to see the corrections. <?php if (!function_exists('json_encode')) { function json_encode($a=false) { if (is_null($a)) return 'null'; if ($a === false) return 'false'; if ($a === true) return 'true'; if (is_scalar($a)) { if (is_float($a)) { // Always use "." for floats. return floatval(str_replace(",", ".", strval($a))); } if (is_string($a)) { static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"')); return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"'; } else return $a; } $isList = true; for ($i = 0, reset($a); $i < count($a); $i++, next($a)) { if (key($a) !== $i) { $isList = false; break; } } $result = array(); if ($isList) { foreach ($a as $v) $result[] = php2js($v); return '[' . join(',', $result) . ']'; } else { foreach ($a as $k => $v) $result[] = php2js($k).':'.php2js($v); return '{' . join(',', $result) . '}'; } } } ?> ---- Server IP: 209.41.74.194 Probable Submitter: 72.25.179.134 ---- Manual Page -- http://www.php.net/manual/en/function.json-encode.php Edit -- https://master.php.net/note/edit/82903 Del: integrated -- https://master.php.net/note/delete/82903/integrated Del: useless -- https://master.php.net/note/delete/82903/useless Del: bad code -- https://master.php.net/note/delete/82903/bad+code Del: spam -- https://master.php.net/note/delete/82903/spam Del: non-english -- https://master.php.net/note/delete/82903/non-english Del: in docs -- https://master.php.net/note/delete/82903/in+docs Del: other reasons-- https://master.php.net/note/delete/82903 Reject -- https://master.php.net/note/reject/82903 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#138953) next »