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

search for in the

Misc.> <JSON Функции
Last updated: Fri, 22 Aug 2008

view this page in

json_encode

(PHP 5 >= 5.2.0, PECL json:1.2.0-1.2.1)

json_encodeReturns 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.

Список изменений

Версия Описание
5.2.1 Added support to JSON encode basic types

Примеры

Пример #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}

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



Misc.> <JSON Функции
Last updated: Fri, 22 Aug 2008
 
add a note add a note User Contributed Notes
json_encode
spam.goes.in.here AT gmail.com
09-Aug-2008 08:05
For anyone who has run into the problem of private properties not being added, you can simply implement the IteratorAggregate interface with the getIterator() method. Add the properties you want to be included in the output into an array in the getIterator() method and return it.
m dot lebkowski+php at gmail dot com
17-Jul-2008 09:21
For all you making your own json_encode functions. strval(3.4) in some locales will give "3,4", and JS will not accept that. remember to do a str_replace on it. jjoss did it correctly.
Steve
01-May-2008 02:35
(corrected)
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[] = json_encode($v);
      return
'[' . join(',', $result) . ']';
    }
    else
    {
      foreach (
$a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);
      return
'{' . join(',', $result) . '}';
    }
  }
}
?>
Hayley Watson
08-Apr-2008 10:51
@elar:

It looks like your installation of php's "precision" config setting is set to something like 9 digits (instead of the default 14, or the 21 mine is at). The exception is the second-to last one, which is shown to a higher precision. Otherwise it's all just floating-point numbers doing what floating-point numbers do.

At least, I only get those results if I force the precision down to nine digits in v5.2.4.
elar at trigger dot ee
01-Apr-2008 06:20
Seems, that json_encode make some cuts with float type values:
echo json_encode(1234567890.1234567890); // return 1234567890
echo json_encode(1234567.1234567890); // return 1234567.12
echo json_encode(0.01234567890123456789); // return 0.0123456789

And for int type:
echo json_encode(1234567890123456789); // return 1234567890123456789
echo json_encode(12345678901234567890); // return 1.23456789e+19
umbrae at gmail dot com
10-Jan-2008 07:21
A couple bug fixes to my own code.. heh.

1. [] would return false before, because an empty array() == false. Needed ===.

2. Backslashed quotes would mess up formatting. Fixed.

// Pretty print some JSON
function json_format($json)
{
    $tab = "  ";
    $new_json = "";
    $indent_level = 0;
    $in_string = false;

    $json_obj = json_decode($json);

    if($json_obj === false)
        return false;

    $json = json_encode($json_obj);
    $len = strlen($json);

    for($c = 0; $c < $len; $c++)
    {
        $char = $json[$c];
        switch($char)
        {
            case '{':
            case '[':
                if(!$in_string)
                {
                    $new_json .= $char . "\n" . str_repeat($tab, $indent_level+1);
                    $indent_level++;
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case '}':
            case ']':
                if(!$in_string)
                {
                    $indent_level--;
                    $new_json .= "\n" . str_repeat($tab, $indent_level) . $char;
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case ',':
                if(!$in_string)
                {
                    $new_json .= ",\n" . str_repeat($tab, $indent_level);
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case ':':
                if(!$in_string)
                {
                    $new_json .= ": ";
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case '"':
                if($c > 0 && $json[$c-1] != '\\')
                {
                    $in_string = !$in_string;
                }
            default:
                $new_json .= $char;
                break;                   
        }
    }

    return $new_json;
}
umbrae at gmail dot com
10-Jan-2008 05:38
Here's a quick function to pretty-print some JSON. Optimizations welcome, as this was a 10-minute dealie without efficiency in mind:

// Pretty print some JSON
// Takes a JSON string and returns it prettified
// If the JSON is invalid, it will return false.
function json_format($json)
{
    $tab = "  ";
    $new_json = "";
    $indent_level = 0;
    $in_string = false;
   
    $json_obj = json_decode($json);
   
    if(!$json_obj)
        return false;
   
    $json = json_encode($json_obj);
    $len = strlen($json);
   
    for($c = 0; $c < $len; $c++)
    {
        $char = $json[$c];
        switch($char)
        {
            case '{':
            case '[':
                if(!$in_string)
                {
                    $new_json .= $char . "\n" . str_repeat($tab, $indent_level+1);
                    $indent_level++;
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case '}':
            case ']':
                if(!$in_string)
                {
                    $indent_level--;
                    $new_json .= "\n" . str_repeat($tab, $indent_level) . $char;
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case ',':
                if(!$in_string)
                {
                    $new_json .= ",\n" . str_repeat($tab, $indent_level);
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case ':':
                if(!$in_string)
                {
                    $new_json .= ": ";
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case '"':
                $in_string = !$in_string;
            default:
                $new_json .= $char;
                break;                   
        }
    }
   
    return $new_json;
}
Pascal Martineau
10-Jan-2008 05:09
Hi,

I'm using Ilya Remizov's snippet (look above, ... about Cyrillic encoding) to encode in utf8 from latin1, which is a very usefull script to encode recursively an array without taking care of the type of data within the array. 

I've found one problem in his script. You should use "$vars = get_object_vars($var);" instead of "$vars = get_class_vars(get_class($var));" to keep your object vars ok during the encoding.

bye
Curious Carrot
04-Jan-2008 11:51
What would be nifty (although I kind of see why it isn't already included) would be an optional parameter to set the style of quotes used. Because,:

<body onload="playWith($somethingThatHasBeenJsonEncoded);">

Won't work when $somethingThatHasBeenJsonEncoded contains double-quotes (which it will). OK, OK, it's easy to do this:

<body onload='playWith($somethingThatHasBeenJsonEncoded);'>

But still eh?
jjoss
24-Oct-2007 09:07
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) . ' }';
  }
}
?>
jfdsmit at gmail dot com
23-Oct-2007 04:31
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);
}
dennispopel(at)gmail.com
26-Aug-2007 07:43
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
php at mikeboers dot com
05-Jul-2007 04:49
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
sean at awesomeplay dot com
26-May-2007 08:21
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.
rtconner
09-May-2007 09:17
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 at NCTU CSIE
02-May-2007 06:55
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;
  }
rhodes dot aaron at gmail dot com
28-Apr-2007 08:57
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;
even at REMOVESPAM dot hpuls dot no
13-Mar-2007 10:01
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.
bisqwit at iki dot fi
07-Mar-2007 01: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.)
php at koterov dot ru
16-Feb-2007 11: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 10: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 09: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));
}
giunta dot gaetano at sea-aeroportimilano dot it
04-Sep-2006 05: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...

Misc.> <JSON Функции
Last updated: Fri, 22 Aug 2008
 
 
show source | credits | sitemap | contact | advertising | mirror sites