How to Use json_decode () and json_encode () in php

Source: Internet
Author: User

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 ()
Copy codeThe Code is as follows:
<? 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:
Copy codeThe Code is as follows:
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)
}

Copy codeThe Code is as follows:
$ 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:
Copy codeThe Code is as follows:
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.
Copy codeThe Code is as follows:
Echo json_decode ($ data, true );

Result:
Copy codeThe Code is as follows:
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 ()
Copy codeThe Code is as follows:
<? Php
$ Arr = array ('A' => 1, 'B' => 2, 'c' => 3, 'D' => 4, 'E' => 5 );

Echo json_encode ($ arr );
?>

The above routine will output:
Copy codeThe Code is as follows:
{"A": 1, "B": 2, "c": 3, "d": 4, "e": 5}

Example #2 usage of the options parameter in the json_encode () function
Copy codeThe Code is as follows:
<? Php
$ A = array ('<foo>', "'bar'", '"baz"', '& blong &', "\ xc3 \ xa9 ");

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), "\ n ";

$ B = array ();

Echo "Empty array output as array:", json_encode ($ B), "\ n ";
Echo "Empty array output as object:", json_encode ($ B, JSON_FORCE_OBJECT), "\ n ";

$ 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), "\ n ";

$ 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), "\ n ";
?>

The above routine will output:
Copy codeThe Code is as follows:
Normal: ["<foo>", "'bar'", "\" baz \ "", "& blong &", "\ u00e9"]
Tags: ["\ u003Cfoo \ u003E", "'bar'", "\" baz \ "", "& blong &", "\ u00e9"]
Apos: ["<foo>", "\ u0027bar \ u0027", "\" baz \ "", "& blong &", "\ u00e9"]
Quot: ["<foo>", "'bar'", "\ u0022baz \ u0022", "& blong &", "\ u00e9"]
Amp: ["<foo>", "'bar'", "\" baz \ "", "\ u0026blong \ u0026", "\ u00e9"]
Unicode: ["<foo>", "'bar'", "\" baz \ "", "& blong &", "é"]
All: ["\ u003Cfoo \ u003E", "\ u0027bar \ u0027", "\ u0022baz \ u0022", "\ u0026blong \ u0026", "é"]

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
Copy codeThe Code is as follows:
<? 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:
Copy codeThe Code is as follows:
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 "}"

Copy codeThe Code is as follows:
$ Obj-> Name = 'a1'; $ obj-> Number = '2013 ';
$ Obj-> Contno = '000 ';
Echo json_encode ($ obj );

Result:
Copy codeThe Code is as follows:
{"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 characters are returned.

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: info-contact@alibabacloud.com 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.