Considerations for JSON

Source: Internet
Author: User
Tags php class

PHP Native provides the Json_encode () and Json_decode () functions, which are used for encoding, which is used for decoding.

First, Json_encode ()

1234 <?php$arrarray (‘a‘=>1,‘b‘=>2,‘c‘=>3,‘d‘=>4,‘e‘=>5);echojson_encode($arr);?>


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

Let's look at an example of an object conversion:

123456 $obj ->body           =  ' another post ' $obj ->id             =; $obj ->approved       = true; $obj ->favorite_count = 1; $obj ->status         = NULL; echo  json_encode ( $obj


1234567891011 { " body " Code class= "PHP plain" >: "another post" Code class= "PHP plain" > "id" :21, "   Approved " :true, "Favorite_count" :1, "status" :null }

Because JSON accepts only utf-8 encoded characters, the Json_encode () argument must be utf-8 encoded, otherwise it will get a null character or null. This is especially important when using GB2312 encoding in Chinese, or when using ISO-8859-1 encoding in a foreign language.

Second, indexed arrays and associative arrays

PHP supports two arrays, one is an indexed array (indexed array) that only holds "value", and the other is an associative array (associative array) that holds "name value pairs" (name/value).

Because JavaScript does not support associative arrays, json_encode () only converts an indexed array (indexed array) into an array format, and the associative array (associative array) to the object format.

For example, there is now an indexed array

123 $arr= Array(‘one‘‘two‘‘three‘); echojson_encode($arr);


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

If you change it to an associative array:

123 $arr= Array(‘1‘=>‘one‘‘2‘=>‘two‘‘3‘=>‘three‘); echojson_encode($arr);

Output becomes

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

Note that the data format has changed from "[]" (array) to "{}" (object).

If you need to force an "indexed array" into an "object", you can write

1 json_encode( (object)$arr);


1 json_encode ( $arr, JSON_FORCE_OBJECT );

Iii. Conversion of classes (class)

The following is a PHP class:

1234567891011121314151617 classFoo {  constERROR_CODE = ‘404‘;  public$public_ex‘this is public‘;  private$private_ex‘this is private!‘;  protected$protected_ex‘this should be protected‘;   publicfunctiongetErrorCode() {    returnself::ERROR_CODE;  }}

Now, JSON transforms the instance of this class:

12345 $foonew Foo; $foo_json = json_encode($foo); echo$foo_json;

The output is

1 {"public_ex":"this is public"}

As you can see, other things (constants, private variables, methods, and so on) are lost in addition to the public variables.

Iv. Json_decode ()

This function is used to convert the JSON text to the appropriate PHP data structure. Here is an example:

12345 $json‘{"foo": 12345}‘; $obj = json_decode($json); print$obj->{‘foo‘}; // 12345

Typically, Json_decode () always returns a PHP object instead of an array. Like what:

123 $json‘{"a":1,"b":2,"c":3,"d":4,"e":5}‘; var_dump(json_decode($json));

The result is to generate a PHP object:

12345678910 object(stdClass)#1 (5) {  ["a"] => int(1)  ["b"] => int(2)  ["c"] => int(3)  ["d"] => int(4)  ["e"] => int(5)}

If you want to force a PHP associative array to be generated, json_decode () needs to add a parameter of true:

123 $json‘{"a":1,"b":2,"c":3,"d":4,"e":5}‘;   var_dump(json_decode($json,true));

As a result, an associative array is generated:

12345678910 array (5) {  &NBSP; [ "a" ] + int (1) &NBSP; Code class= "PHP plain" > [ "B" ] + int (2) Code class= "php Spaces" >&NBSP; [ "C" ] = Int (3) &NBSP; [ Code class= "PHP string" > "D" ] + int (4)   [ "E" ] + int (5)  }

V. Common errors in Json_decode ()

The following three kinds of JSON notation are wrong, can you see where is wrong?

12345 $bad_json"{ ‘bar‘: ‘baz‘ }"; $bad_json ‘{ bar: "baz" }‘; $bad_json‘{ "bar": "baz", }‘;

Executing Json_decode () on these three strings will return null and error.

The first error is that the JSON delimiter (delimiter) only allows double quotation marks and cannot use single quotes. The second error is the "name" of the JSON name-value pair (the left part of the colon), which must use double quotes in any case. The third error is that you cannot add a comma after the last value (trailing comma).

In addition, JSON can only be used to represent objects (object) and Arrays (array), and if you use Json_decode () for a string or numeric value, NULL will be returned.

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

Considerations for JSON

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.