PHP: json_encode - Manual

downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

kadm5 json_decode

Last updated: Sat, 27 Jan 2007

view this page in

# json_encode

(no version information, might be only in CVS)

json_encode -- Returns the JSON representation of a value

## Описание

string json_encode ( mixed value )

Returns a string containing the JSON representation of `value`.

## Список параметров

`value`

  The `value` being encoded. Can be any type except a resource.

  This function only works with UTF-8 encoded data.

## Возвращаемые значения

Returns a JSON encoded string on success.

## Примеры

Пример 1. A json_encode() example

`<?php $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); echo json_encode($arr); ?>`

Результат выполнения данного примера:

    {"a":1,"b":2,"c":3,"d":4,"e":5}

## Смотрите также

json_decode()

add a note User Contributed Notes
json_encode
bisqwit at iki dot fi
07-Mar-2007 04:08
`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.)`
bisqwit at iki dot fi
07-Mar-2007 02:47
`Here's a slightly simpler binary-safe version of json_encode. Note that associative array keys are converted to strings to comply with the official json specification. (Arrays with all-numeric keys in a pure sequence are converted to lists instead.)
function myjson($s)
{
if(is_numeric($s)) return $s;
if(is_string($s)) return 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';
}
Of course it'd be nice if this hack wasn't required in the first place...`
David Gillies (daggillies-AT-gmail.com
23-Feb-2007 10:32
`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));
}`
php at koterov dot ru
16-Feb-2007 02:43
`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.`
Ilya Remizov <q-snick at mail dot ru>
19-Jan-2007 01:04
`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;
}`
Andrea Giammarchi
19-Nov-2006 12: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 11: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 08: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 04: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).`
add a note
kadm5 json_decode

Last updated: Sat, 27 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 09:32:46 2007 PST