One of the purpose of JSON is to be easy for humans to read and write. But the output of json_encode() doen't indent very nicely... a "flat" string !
This function might help to have a nice identation :)
<?php
echo indentJson(json_encode($anArray));
function indentJson($str){
$strOut = '';
$identPos = 0;
for($loop = 0;$loop<= strlen($str) ;$loop++){
$_char = substr($str,$loop,1);
//part 1
if($_char == '}' || $_char == ']'){
$strOut .= chr(13);
$identPos --;
for($ident = 0;$ident < $identPos;$ident++){
$strOut .= chr(9);
}
}
//part 2
$strOut .= $_char;
//part 3
if($_char == ',' || $_char == '{' || $_char == '['){
$strOut .= chr(13);
if($_char == '{' || $_char == '[')
$identPos ++;
for($ident = 0;$ident < $identPos;$ident++){
$strOut .= chr(9);
}
}
}
return $strOut;
?>
json_encode
(no version information, might be only in CVS)
json_encode -- Returns the JSON representation of a valueDescription
string json_encode ( mixed value )Returns a string containing the JSON representation of value.
json_encode
fudriot at omic dot ch
25-Nov-2006 03:27
25-Nov-2006 03:27
Andrea Giammarchi
19-Nov-2006 02:48
19-Nov-2006 02:48
// ... and this is performance/memory optimized version :)
function json_real_encode($obj){
$f = $r = array();
foreach(array_merge(range(0, 7), array(11), range(14, 31)) as $v) {
$f[] = chr($v);
$r[] = "\\u00".sprintf("%02x", $v);
}
return str_replace($f, $r, json_encode($obj));
}
Andrea Giammarchi
18-Nov-2006 01:24
18-Nov-2006 01:24
// 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)
);
}
giunta dot gaetano at sea-aeroportimilano dot it
04-Sep-2006 10:11
04-Sep-2006 10:11
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...
RQuadling at GMail dot com
01-Sep-2006 07:40
01-Sep-2006 07:40
In trying to get an array which contains &, " ' in it into a JS select took me a little while.
My solution is a combination of htmlentites() and addslashes(), just like any other sort of data output.
The example code takes an array and creates a JS object (as the PHP variable is an associative array).
I also use both single and double quotes in the eval statement to prove resilience.
See http://rquadling.php1h.com/ for this and other usefull info.
<?php
// Define array with missing indexes.
$a_List = array
(
0 => 'Examine Locks',
1 => 'Get Grade',
2 => 'Get Manufacturer',
3 => "Get Manufacturer's Pattern", // unescaped '
6 => 'Get Mould Number',
7 => 'Validate A&R', // & will become &
'Quote' => '"The answer is : 42".', // " will becode "
'Last' => 'Quit Process',
);
// Make sure any HTML Entities are not sent unescaped.
foreach($a_List as $m_Key => $m_Value)
{
$a_List[$m_Key] = htmlentities($m_Value);
}
// JSON Encode the list
$s_JSON_Encoded = addslashes(json_encode($a_List));
// Get the list into simple variable for printing.
$s_List = var_export($a_List, True);
// Output the results along with some JS to show what was received.
echo <<< END_TEXT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>JSON test</title>
</head>
<body>
<div>Original Data : <pre>$s_List</pre></div>
<div>JSON Encoded : <pre>$s_JSON_Encoded</pre></div>
<div>JSON Decoded : <pre><script language="JavaScript" type="text/javascript">
var obj_dq = eval("($s_JSON_Encoded)");
var obj_sq = eval('($s_JSON_Encoded)');
var s_dq = '';
var s_sq = '';
for(var s_label in obj_dq)
{
s_dq = s_dq + '\\n' + s_label + ' => ' + obj_dq[s_label] + ',';
}
for(var s_label in obj_sq)
{
s_sq = s_sq + '\\n' + s_label + ' => ' + obj_sq[s_label] + ',';
}
document.writeln(s_dq + '\\n' + s_sq);
</script></pre></div>
</body>
</html>
END_TEXT;
?>
RQuadling at GMail dot com
01-Sep-2006 06:54
01-Sep-2006 06:54
Contrary to the manual as at 2006/09/01, the only types that can be json_encode'd are arrays and objects.
See http://bugs.php.net/bug.php?id=38680 for a script to show things working (or not).
