Json_decode () and json_encode () in php ()
1. json_decode ()
Json_decode
(PHP 5> = 5.2.0, PECL json> = 1.2.0)
Json_decode-encode strings in JSON format
Description
Mixed json_decode (string $ json [, bool $ assoc])
Accept a JSON string and convert it to a PHP variable
Parameters
Json
A string in json string format.
Assoc
If this parameter is set to TRUE, array instead of object is returned.
Return value
Returns an object or if the optional assoc parameter is TRUE, an associative array is instead returned.
Example
Example #1 Example of json_decode ()
The code is as follows: |
Copy code |
<? Php $ Json = '{"a": 1, "B": 2, "c": 3, "d": 4, "e": 5 }'; Var_dump (json_decode ($ json )); Var_dump (json_decode ($ json, true )); ?> The above example will output: Object (stdClass) #1 (5 ){ ["A"] => int (1) ["B"] => int (2) ["C"] => int (3) ["D"] => int (4) ["E"] => int (5) } Array (5 ){ ["A"] => int (1) ["B"] => int (2) ["C"] => int (3) ["D"] => int (4) ["E"] => int (5) } $ Data = '[{"Name": "a1", "Number": "123", "Contno": "000", "QQNo ":""}, {"Name": "a1", "Number": "123", "Contno": "000", "QQNo": "" },{ "Name ": "a1", "Number": "123", "Contno": "000", "QQNo": ""}] '; Echo json_decode ($ data );
Result: Array ([0] => stdClass Object ([Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] =>) [1] => stdClass Object ([Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] =>) [2] => stdClass Object ([Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => )) |
It can be seen that the object compiled by json_decode () is an object. Now, output json_decode ($ data, true) and try again.
The code is as follows: |
Copy code |
Echo json_decode ($ data, true ); Result: Array ([0] => Array ([Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] =>) [1] => Array ([Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] =>) [2] => Array ([Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => )) |
We can see an associated array output by json_decode ($ data, true). From this we can see that json_decode ($ data) outputs an object, while json_decode ("$ arr", true) is to force generate PHP associated array.
2. json_encode ()
Json_encode
(PHP 5> = 5.2.0, PECL json> = 1.2.0)
Json_encode-JSON encoding of variables
Report a bug description
String json_encode (mixed $ value [, int $ options = 0])
Return the JSON format of the value.
Report a bug parameters
Value
Value to be encoded. It can be of any data type except the resource type.
This function can only accept UTF-8-encoded data
Options
Binary mask composed of the following constants: JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, response, JSON_FORCE_OBJECT.
Report a bug return value
If the encoding is successful, a string in JSON format is returned or FALSE is returned if the encoding fails.
Report a bug update log
Version description
5.4.0 the options parameter adds constants: JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, and JSON_UNESCAPED_UNICODE.
5.3.3 constant added to the options parameter: JSON_NUMERIC_CHECK.
5.3.0 adds the options parameter.
Example of Report a bug
Example #1 Example of A json_encode ()
The code is as follows: |
Copy code |
<? Php $ Arr = array ('a' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5 ); Echo json_encode ($ arr ); ?> The above routine will output: {"A": 1, "B": 2, "c": 3, "d": 4, "e": 5} Example #2 usage of the options parameter in the json_encode () function <? Php $ A = array ('<foo>', "'bar'", '"baz"', '& blong &', "xc3xa9 "); Echo "Normal:", json_encode ($ a), "n "; Echo "Tags:", json_encode ($ a, JSON_HEX_TAG), "n "; Echo "Apos:", json_encode ($ a, JSON_HEX_APOS), "n "; Echo "Quot:", json_encode ($ a, JSON_HEX_QUOT), "n "; Echo "Amp:", json_encode ($ a, JSON_HEX_AMP), "n "; Echo "Unicode:", json_encode ($ a, JSON_UNESCAPED_UNICODE), "n "; Echo "All:", json_encode ($ a, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE), "nn "; $ B = array (); Echo "Empty array output as array:", json_encode ($ B), "n "; Echo "Empty array output as object:", json_encode ($ B, JSON_FORCE_OBJECT), "nn "; $ C = array (1, 2, 3 )); Echo "Non-associative array output as array:", json_encode ($ c), "n "; Echo "Non-associative array output as object:", json_encode ($ c, JSON_FORCE_OBJECT), "nn "; $ D = array ('foo' => 'bar', 'Baz' => 'long '); Echo "Associative array always output as object:", json_encode ($ d), "n "; Echo "Associative array always output as object:", json_encode ($ d, JSON_FORCE_OBJECT), "nn "; ?> The above routine will output: Normal: ["<foo>", "'bar'", "" baz "", "& blong &", "u00e9"] Tags: ["u003Cfoou003E", "'bar'", "" baz "", "& blong &", "u00e9"] Apos: ["<foo>", "u0027baru0027", "" baz "", "& blong &", "u00e9"] Quot: ["<foo>", "'bar'", "u0022bazu0022", "& blong &", "u00e9"] Amp: ["<foo>", "'bar'", "" baz "", "u0026blongu0026", "u00e9"] Unicode: ["<foo>", "'bar'", "" baz "", "& blong &", "& eacute;"] All: ["u003Cfoou003E", "u0027baru0027", "u0022bazu0022", "u0026blongu0026", "& eacute;"] Empty array output as array: [] Empty array output as object :{} Non-associative array output as array: [[1, 2, 3] Non-associative array output as object: {"0": {"0": 1, "1": 2, "2": 3 }} Associative array always output as object: {"foo": "bar", "baz": "long "} Associative array always output as object: {"foo": "bar", "baz": "long "} |
Example #3 examples of continuous and non-continuous arrays
The code is as follows: |
Copy code |
<? Php Echo "continuous array". PHP_EOL; $ Sequential = array ("foo", "bar", "baz", "blong "); Var_dump ( $ Sequential, Json_encode ($ sequential) ); Echo PHP_EOL. "discontinuous array". PHP_EOL; $ Nonsequential = array (1 => "foo", 2 => "bar", 3 => "baz", 4 => "blong "); Var_dump ( $ Nonsequential, Json_encode ($ nonsequential) ); Echo PHP_EOL. "An discontinuous array generated by deleting a continuous array value". PHP_EOL; Unset ($ sequential [1]); Var_dump ( $ Sequential, Json_encode ($ sequential) ); ?> |
The above routine will output:
The code is as follows: |
Copy code |
Continuous array Array (4 ){ [0] => String (3) "foo" [1] => String (3) "bar" [2] => String (3) "baz" [3] => String (5) "blong" } String (27) "[" foo "," bar "," baz "," blong "]" Non-continuous array Array (4 ){ [1] => String (3) "foo" [2] => String (3) "bar" [3] => String (3) "baz" [4] => String (5) "blong" } String (43) "{" 1 ":" foo "," 2 ":" bar "," 3 ":" baz "," 4 ":" blong "}" Deletes a continuous array value. Array (3 ){ [0] => String (3) "foo" [2] => String (3) "baz" [3] => String (5) "blong" } String (33) "{" 0 ":" foo "," 2 ":" baz "," 3 ":" blong "}" $ Obj-> Name = 'A1'; $ obj-> Number = '2013 '; $ Obj-> Contno = '000 '; Echo json_encode ($ obj );
Result: {"Name": "a1 ", "Number": "123 ", "Contno": "000" } |
It can be seen that json_encode () and json_decode () are compilation and decompilation processes. Note that json only accepts UTF-8 characters. Therefore, the json_encode () parameter must be UTF-8 encoded, otherwise, null or null is returned.
If it is Chinese, pay attention to it.
Find a solution on the Internet:
The code is as follows: |
Copy code |
<? Php /* Process json_encode Chinese garbled characters */ $ Data = array ('game' => 'ice-fire status', 'name' => 'Thorn Spirit ', 'Country' => 'ice-Frome status ', 'level' => 45 ); Echo json_encode ($ data ); Echo "<br> "; $ NewData = array (); Foreach ($ data as $ key => $ value ){ $ NewData [$ key] = urlencode ($ value ); } Echo urldecode (json_encode ($ newData )); ?> |
Later, I consulted someone and I could use base64 encoding. However, base64 encoding cannot be placed in URLs. Baidu explained this as follows:
The standard Base64 is not suitable for direct transmission in the URL, because the URL encoder will convert the "/" and "+" characters in the standard Base64 into the form of "% XX, these "%" signs need to be converted when they are stored in the database, because "%" has been used as a wildcard in ansi SQL.
However, my data is sent through POST, not in the HTTP head, but in the message-body, so it is not affected.
Json_encode can only accept UTF-8 data
For example, if 'signature' is changed to 'u80e5' after json_encode processing, the Chinese part of the final json is replaced with unicode encoding. What we need to solve is to convert the object to json and ensure that the Chinese character inside the object still appears in json as normal Chinese. Now it seems that json_encode alone cannot achieve the goal.
My solution: perform url encoding for the Chinese fields in the class first, then perform json encoding (jsonencode) for the object, and finally url decoding (urldecode) json, that is, the final json. The Chinese in it is still the Chinese!
The test code is as follows:
The code is as follows: |
Copy code |
<? Php Class myClass { Public $ item1 = 1; Public $ item2 = 'Chinese '; Function to_json (){ // Url encoding to avoid converting Chinese to unicode using json_encode $ This-> item2 = urlencode ($ this-> item2 ); $ Str_json = json_encode ($ this ); // Url decoding. After converting json, all attributes are returned, so that the object attributes remain unchanged. $ This-> item2 = urldecode ($ this-> item2 ); Return urldecode ($ str_json ); } } $ C = new myClass (); Echo json_encode ($ c ); Echo '<br/> '; Echo $ c-> to_json (); Echo '<br/> '; Echo json_encode ($ c ); Echo '<br/> '; Echo json_encode ('authorization '); ?> Program output result: {"Item1": 1, "item2": "u4e2du6587 "} {"Item1": 1, "item2": "Chinese "} {"Item1": 1, "item2": "u4e2du6587 "} "U80e5"
|