|
json_encode
Returns the JSON representation of a value
(PHP 5 >= 5.2.0, PECL json:1.2.0-1.2.1)
Example 1099. A json_encode() example<?php The above example will output: {"a":1,"b":2,"c":3,"d":4,"e":5} Code Examples / Notes » json_encodebisqwit
This is an update to my previous post. The previous one did not handle null characters (and other characters from 00..1F range) properly. This does. function myjson($s) { if(is_numeric($s)) return $s; if(is_string($s)) return preg_replace("@([\1-\037])@e", "sprintf('\\\\u%04X',ord('$1'))", str_replace("\0", '\u0000', utf8_decode(json_encode(utf8_encode($s))))); if($s===false) return 'false'; if($s===true) return 'true'; if(is_array($s)) { $c=0; foreach($s as $k=>&$v) if($k !== $c++) { foreach($s as $k=>&$v) $v = myjson((string)$k).':'.myjson($v); return '{'.join(',', $s).'}'; } return '[' . join(',', array_map('myjson', $s)) . ']'; } return 'null'; } (Now I just hope the comment posting form doesn't do anything funny to backslashes and quotes.) php_dev
The obvious use of this function is to transmit data objects via a web server to a web page via AJAX. Here is the simple way to convert the data into a javascript object (or data structure) once received: <script type='text/javascript'> function json_decode(jsonstr) { data = eval('('+jsonstr+')'); return data; } </script> rtconner
That last note by me implies that you either dont want to install json or are not able to install json for one reason or another. It is just a way to emulate simpler (and common) json ability without installing the library.
giunta dot gaetano
Take care that json_encode() expects strings to be encoded to be in UTF8 format, while by default PHP strings are ISO-8859-1 encoded. This means that json_encode(array('à ü')); will produce a json representation of an empty string, while json_encode(array(utf8_encode('à ü'))); will work. The same applies to decoding, too, of course... dennispopel
Obviously, this function has trouble encoding arrays with empty string keys (''). I have just noticed that (because I was using a function in PHP under PHP4). When I switched to PHP5's json_encode, I noticed that browsers could not correctly parse the encoded data. More investigation maybe needed for a bug report, but this quick note may save somebody several hours. Also, it manifests on Linux in 5.2.1 (tested on two boxes), on my XP with PHP5.2.3 json_encode() works just great! However, both 5.2.1 and 5.2.3 phpinfo()s show that the json version is 1.2.1 so might be Linux issue sean
jtconner, That code is horrendously broken for an array that contains anything other than integer values. You need to do things much better than that to handle any kind of real-world data. Here's something similar to what I use (off the top of my head). Note that it will break horribly on recursive arrays. Disclaimer: this is off the top of my head, it might have a few typos or other mistakes. function jsValue(&$value) { switch(gettype($value)) { case 'double': case 'integer': return $value; case 'bool': return $value?'true':'false'; case 'string': return '\''.addslashes($value).'\''; case 'NULL': return 'null'; case 'object': return '\'Object '.addslashes(get_class($value)).'\''; case 'array': if (isVector($value)) return '['.implode(',', array_map('jsValue', $value)).']'; else { $result = '{'; foreach ($value as $k=>$v) { if ($result != '{') $result .= ','; $result .= jsValue($k).':'.jsValue($v); } return $result.'}'; } default: return '\''.addslashes(gettype($value)).'\''; } NOTE: the isVector() function call is one that checks to see if the PHP array is actually a vector (an array with integer keys starting at 0) or a map (an associative array, which may include a sparse integer-only-keyed array). The function looks like: function isVector (&$array) { $next = 0; foreach ($array as $k=>$v) { if ($k != $next) return false; $next++; } return true; } By using that test, it's guaranteed that you will always send correct results to Javascript. The only time that might fail is if you have a vector and delete a few keys without compacting the array back down - it'll detect it as a map. But, technically, that's correct, since that's how PHP arrays behave. The function is capable of taking any PHP type and returning something, and it should be impossible to get it to return anything that's un-safe or incorrect. jfdsmit
json_encode also won't handle objects that do not directly expose their internals but through the Iterator interface. These two function will take care of that: <?php /** * Convert an object into an associative array * * This function converts an object into an associative array by iterating * over its public properties. Because this function uses the foreach * construct, Iterators are respected. It also works on arrays of objects. * * @return array */ function object_to_array($var) { $result = array(); $references = array(); // loop over elements/properties foreach ($var as $key => $value) { // recursively convert objects if (is_object($value) || is_array($value)) { // but prevent cycles if (!in_array($value, $references)) { $result[$key] = object_to_array($value); $references[] = $value; } } else { // simple values are untouched $result[$key] = $value; } } return $result; } /** * Convert a value to JSON * * This function returns a JSON representation of $param. It uses json_encode * to accomplish this, but converts objects and arrays containing objects to * associative arrays first. This way, objects that do not expose (all) their * properties directly but only through an Iterator interface are also encoded * correctly. */ function json_encode2($param) { if (is_object($param) || is_array($param)) { $param = object_to_array($param); } return json_encode($param); } ilya remizov
In case of problems with Cyrillic you may use these helpful functions ( use json_safe_encode() instead of json_encode() ): define('DEFAULT_CHARSET', 'cp1251'); function json_safe_encode($var) { return json_encode(json_fix_cyr($var)); } function json_fix_cyr($var) { if (is_array($var)) { $new = array(); foreach ($var as $k => $v) { $new[json_fix_cyr($k)] = json_fix_cyr($v); } $var = $new; } elseif (is_object($var)) { $vars = get_class_vars(get_class($var)); foreach ($vars as $m => $v) { $var->$m = json_fix_cyr($v); } } elseif (is_string($var)) { $var = iconv(DEFAULT_CHARSET, 'utf-8', $var); } return $var; } rtconner
If you just want simple arrays converted to JS format, you can use this. <?php // a simple array echo 'new Array('.implode(', ', $my_array).')'; // an associative array foreach($my_array as $key=>$val) $arr[] = "\"$key\":$val"; echo '{'.implode(', ', $arr).'}'; ?> yi-ren chen
I write a function "php_json_encode" for early version of php which support "multibyte" but doesn't support "json_encode". <?php function json_encode_string($in_str) { mb_internal_encoding("UTF-8"); $convmap = array(0x80, 0xFFFF, 0, 0xFFFF); $str = ""; for($i=mb_strlen($in_str)-1; $i>=0; $i--) { $mb_char = mb_substr($in_str, $i, 1); if(mb_ereg("&#(\\d+);", mb_encode_numericentity($mb_char, $convmap, "UTF-8"), $match)) { $str = sprintf("\\u%04x", $match[1]) . $str; } else { $str = $mb_char . $str; } } return $str; } function php_json_encode($arr) { $json_str = ""; if(is_array($arr)) { $pure_array = true; $array_length = count($arr); for($i=0;$i<$array_length;$i++) { if(! isset($arr[$i])) { $pure_array = false; break; } } if($pure_array) { $json_str ="["; $temp = array(); for($i=0;$i<$array_length;$i++) { $temp[] = sprintf("%s", php_json_encode($arr[$i])); } $json_str .= implode(",",$temp); $json_str .="]"; } else { $json_str ="{"; $temp = array(); foreach($arr as $key => $value) { $temp[] = sprintf("\"%s\":%s", $key, php_json_encode($value)); } $json_str .= implode(",",$temp); $json_str .="}"; } } else { if(is_string($arr)) { $json_str = "\"". json_encode_string($arr) . "\""; } else if(is_numeric($arr)) { $json_str = $arr; } else { $json_str = "\"". json_encode_string($arr) . "\""; } } return $json_str; } florent
I thought json_encode() was an easy way to obtain a JSON expression for my objects until I realized that private / protected values would not be processed ... class MyObject { private $id; private $name; public function _construct ($id, $name) { $this->id = $id; $this->name = $name; } public function toJson() { return json_encode($this); } } $o = new MyObject('001', 'foo'); $json = $o->toJson(); echo $json; -> {} php
Here is a way to convert an object to an array which will include all protected and private members before you send it to json_encode() <?php function objectArray( $object ) { if ( is_array( $object )) return $object ; if ( !is_object( $object )) return false ; $serial = serialize( $object ) ; $serial = preg_replace( '/O:\d+:".+?"/' ,'a' , $serial ) ; if( preg_match_all( '/s:\d+:"\\0.+?\\0(.+?)"/' , $serial, $ms, PREG_SET_ORDER )) { foreach( $ms as $m ) { $serial = str_replace( $m[0], 's:'. strlen( $m[1] ) . ':"'.$m[1] . '"', $serial ) ; } } return @unserialize( $serial ) ; } // TESTING class A { public $a = 'public for a' ; protected $b = true ; private $c = 123 ; } class B { public $d = 'public for b' ; protected $e = false ; private $f = 456 ; } $a = new A() ; $a -> d = new B() ; echo '<pre>' ; print_r( $a ) ; print_r( objectArray( $a )) ; ?> Cheers! mike rhodes dot aaron
For the functions below, you can't make the following assumption: if(is_numeric($s)) return $s; The reason being that in the case of strings consisting of all numbers and leading zeros (zip codes, ssn numbers, bar codes, ISBN numbers, etc), the leading zeros will be dropped. Instead, make sure your variables are the correct data types and use: if(is_int($s) || is_float($s)) return $s; php
Could you please explain why json_encode() takes care about the encoding at all? Why not to treat all the string data as a binary flow? This is very inconvenient and disallows the usage of json_encode() in non-UTF8 sites! :-( I have written a small substitution for json_encode(), but note that it of course works much more slow than json_encode() with big data arrays.. /** * Convert PHP scalar, array or hash to JS scalar/array/hash. */ function php2js($a) { if (is_null($a)) return 'null'; if ($a === false) return 'false'; if ($a === true) return 'true'; if (is_scalar($a)) { $a = addslashes($a); $a = str_replace("\n", '\n', $a); $a = str_replace("\r", '\r', $a); $a = preg_replace('{(</)(script)}i', "$1'+'$2", $a); 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) . ' }'; } } So, my suggestion is remove all string analyzation from json_encode() code. It also make this function to work faster. jjoss
Another way to work with Russian characters. This procedure just handles Cyrillic characters without UTF conversion. Thanks to JsHttpRequest developers. <?php function php2js($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. $a = str_replace(",", ".", strval($a)); } // All scalars are converted to strings to avoid indeterminism. // PHP's "1" and 1 are equal for all PHP operators, but // JS's "1" and 1 are not. So if we pass "1" or 1 from the PHP backend, // we should get the same result in the JS frontend (string). // Character replacements for JSON. static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"')); return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $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) . ' }'; } } ?> david gillies daggillies-at-gmail.com
Although it is perfectly legal to hand back non-XML data as a response to an AJAX request, under Firefox this will trigger a warning. The simple solution is to wrap the JSON string in a trivial XML document. I have a simple function called json_message() which does this: function json_message($message) { ob_start(); echo "<?xml version=\"1.0\" standalone=\"yes\" ?>\n"; echo "<json>".rawurlencode( json_encode( $message) )."</json>\n"; $resp=ob_get_clean(); return $resp; } The companion function JavaScript side is get_json_message(): function get_json_message(str) { var spos=str.indexOf('<json>'); var epos=str.indexOf('</json>'); return unescape(str.substring(spos+6,epos)); } even
A follow-up to the post of Ilya Remizov <q-snick at mail dot ru>: The part in the code dealing with objects has to be replaced from $vars = get_class_vars(get_class($var)); to e.g. this: $vars = get_obj_vars($var); If not, you will only get NULL values on the properties, because the values are from the class definition, not the object instance. andrea giammarchi
// fixes unconverted chars in range 00-1f function json_real_encode($obj){ $range = array_merge(range(0, 7), array(11), range(14, 31)); return str_replace( array_map(create_function('&$i', 'return chr($i);'), $range), array_map(create_function('&$i', 'return $i ? "\\u00".sprintf("%02x", $i) : "\\u0000";'), $range), json_encode($obj) ); } |