Technical Articles => Web =>  PHP

Using JSON in PHP

Source : Peter    Date : 2012-05-06 06:04:42  

Currently JSON has become one of the most popular data exchange formats. Many website APIs support it. Since PHP 5.2, PHP provides json_encode() and json_decode() method to handle JSON encoding and decoding.

1. json_encode()

This function is used to transform array and objects to JSON format. First let's look one array example.

        $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

  echo json_encode($arr);

the result is

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

We look one example of object transformation.

        $obj->body = 'another post';

  $obj->id = 21;

  $obj->approved = true;

  $obj->favorite_count = 1;

  $obj->status = NULL;

  echo json_encode($obj);

the result is

        {
    "body":"another post",

    "id":21,

    "approved":true,

    "favorite_count":1,

    "status":null
  }

Since JSON can only accept UTF-8 encoded characters, so parameters of json_encode() must be utf-8 encoded, otherwise the result will be empty or null. So we need to take care when we use Chinese's GB2312 encoding or some other languages' ISO-8859-1 encoding.

2. Indexed array and associative array

PHP supports two kinds of arrays, one is indexed array which only stores the value, the other is associative array which stores name/value pairs.

Since JavaScript doesn't support associative array, so json_encode() will transform indexed array into array format, while transform associative array into object format.

For example, we have an indexed array

        $arr = Array('one', 'two', 'three');

  echo json_encode($arr);

the result will be

        ["one","two","three"]

If we have an associative array

        $arr = Array('1'=>'one', '2'=>'two', '3'=>'three');

  echo json_encode($arr);

the result will be

        {"1":"one","2":"two","3":"three"}

Note, data format has changed from [] to {}.

If you want to forcibly transform indexed array into object, you can

      json_encode( (object)$arr );

or

      json_encode ( $arr, JSON_FORCE_OBJECT );

3. Transformation of class

Here is a PHP class
      class Foo {

    const ERROR_CODE = '404';

    public $public_ex = 'this is public';

    private $private_ex = 'this is private!';

    protected $protected_ex = 'this should be protected';

    public function getErrorCode() {

      return self::ERROR_CODE;

    }

  }

now we do JSON transformation.

        $foo = new Foo;

  $foo_json = json_encode($foo);

  echo $foo_json;

the result is

        {"public_ex":"this is public"}

we can see that only public variables are transformed. All rest will be ignored.

4. json_decode()

To transform JSON data to PHP data structure. For example

       $json = '{"foo": 12345}';

  $obj = json_decode($json);

  print $obj->{'foo'}; // 12345

Usually, json_decode() will return a PHP object instead of array.

        $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

  var_dump(json_decode($json));

the result is a PHP object

        object(stdClass)#1 (5) {

    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)

  }

If we want to forcibly to transform JSON into an array, we need to add one more parameter true to json_decode().

        $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

  var_dump(json_decode($json,true));

the result is an associative array

        array(5) {

     ["a"] => int(1)
     ["b"] => int(2)
     ["c"] => int(3)
     ["d"] => int(4)
     ["e"] => int(5)

  }

5. Common mistakes of json_decode()

Following three JSON example have syntax errors. Where is the error?

        $bad_json = "{ 'bar': 'baz' }";

  $bad_json = '{ bar: "baz" }';

  $bad_json = '{ "bar": "baz", }';

the json_decode() will return null for the above three strings.

The first error is, delimiter of JSON can only be double quote, cannot be single quote. The second error is the name of the name/value pair of JSON must be surrounded with double quote. The last error is the last value cannot have trailing comma.

Also JSON can only be used to represent object and array, if we use json_decode() on a string or number, it will return null.

        var_dump(json_decode("Hello World")); //null

References

        * PHP Manual

  * Ed Finkler, JSON is Everybody's Friend

Original author : 阮一峰 Source : http://www.ruanyifeng.com/blog/2011/01/json_in_php.html

Save as PDF Mark as read Mark as important
By clicking the "Mark as read" button, this article will be marked as read. It will be removed from the homepage's latest news and the article list on the "Technical article" page in following visits and it will be put to your read list which you can find in "Amin->Article read list". There you can unmark the read articles.
By clicking the "Mark as important" button, this article will be put to your important article list which you can find in "Amin->Article important list". Later when you want reread this article, it's easier for you to find it by checking the "Article important list".

Tags:JSON,PHP,json_decode(0,json_encode()   Read(6145) Comment(1)

Share on Facebook  Share on Twitter  Share on Google+  Share on Weibo  Share on Digg  Share on Tumblr    Delicious 

 Previous : this in JavaScript
 Next : Unix Philosophy

  ::Related Articles

  ::Comment Zone

joelmob (joel.moberg@gmail.com) [Reply]@ 2012-05-07 08:59:42
Here is a snippet on how to get JSON from your SQL server with PHP and MySQLi

  ::Comment

Nickname  
Email 
Comment

:: Other versions

No other versions available yet.

:: Recent articles

:: Most read

:: Most commented

:: Contribute

Want to share with the world your understanding about technology? Want to record the process you solve a technical problem? Want to make the world benefit from your understanding and solution? Write them down. You make the world better, the world makes us better.

 Write article

:: Find us

Back to top