How to use Json_decode () and Json_encode () in PHP _php tips

Source: Internet
Author: User
Tags array example mixed string format

1.json_decode ()

Json_decode
(PHP 5 >= 5.2.0, PECL json >= 1.2.0)

json_decode-strings encoded in JSON format

Description
Mixed Json_decode (String $json [, bool $assoc])
Accepts a JSON-formatted string and converts it to a PHP variable

Parameters

Json
A string in JSON string format to be decoded.

Assoc
When this argument is TRUE, the array is returned instead of object.


return value
Returns an object or if the optional assoc parameter is TRUE, a associative array is instead returned.

Example

Examples of Example #1 Json_decode ()

Copy Code code 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 example above will output:
Copy Code code 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 Code code as follows:

$data = ' [{' Name]: ' A1 "," Number ":" 123 "," Contno ":" "," qqno ":" "},{" Name ":" A1 "," Number ":" 123 "," Contno ":" "," qqno ":" "},{" "Name": "A1", "Number": "123", "Contno": "V", "qqno": ""}] ';
echo Json_decode ($data);

The results are:
Copy Code code as follows:

Array ([0] => stdClass Object ([Name] => A1 [number] => 123 [Contno] => [qqno] =>) [1] => Stdclas s Object ([name] => A1 [number] => 123 [Contno] => [qqno] =>) [2] => stdClass Object ([name] => a 1 [number] => 123 [Contno] => [qqno] =>))

It can be seen that the object is compiled by Json_decode (), now output Json_decode ($data, true) to try
Copy Code code as follows:

Echo Json_decode ($data, true);

Results:
Copy Code code as follows:

Array ([0] => Array ([name] => A1 [number] => 123 [Contno] => [qqno] =>) [1] => Array ([name] =& Gt A1 [number] => 123 [Contno] => [qqno] =>) [2] => Array ([Name] => A1 [number] => 123 [Contno] => ; [Qqno] =>)

You can see an associative array of Json_decode ($data, true) output, so that Json_decode ($data) output is an object, and Json_decode ("$arr", true) forces it to generate a PHP associative array.

2.json_encode ()

Json_encode
(PHP 5 >= 5.2.0, PECL json >= 1.2.0)

json_encode-JSON encoding of a variable

Statement a bug description
String Json_encode (mixed $value [, int $options = 0])
Returns the JSON form of value values

A bug parameter

Value
The value to be encoded, in addition to the resource type, can be any data type

This function can only accept UTF-8 encoded data

Options
A binary mask consisting of the following constants: Json_hex_quot, Json_hex_tag, Json_hex_amp, Json_hex_apos, Json_numeric_check, Json_pretty_print, JSON_ Unescaped_slashes, Json_force_object, Json_unescaped_unicode.

A bug return value
The encoding succeeds by returning a string in the form of JSON or FALSE on failure.

A Bug update log
Version description
5.4.0 Options Parameters Add constants: Json_pretty_print, Json_unescaped_slashes, and Json_unescaped_unicode.
5.3.3 Options parameter Add constant: Json_numeric_check.
5.3.0 add options parameter.


A bug example

Example of Example #1 a Json_encode ()
Copy Code code as follows:

<?php
$arr = Array (' A ' =>1, ' B ' =>2, ' C ' =>3, ' d ' =>4, ' e ' =>5);

echo Json_encode ($arr);
?>

The above routines will output:
Copy Code code as follows:

{"A": 1, "B": 2, "C": 3, "D": 4, "E": 5}

Example #2 The use of the options parameter in the Json_encode () function
Copy Code code 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 (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 routines will output:
Copy Code code 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& "," E "]
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 OUTPU T as object: {"foo": "Bar", "baz": "Long"}

Example #3 continuous and discontinuous array example
Copy Code code as follows:

<?php
echo "contiguous array". Php_eol;
$sequential = Array ("foo", "Bar", "Baz", "Blong");
Var_dump (
$sequential,
Json_encode ($sequential)
);

echo Php_eol. " Non-contiguous array ". Php_eol;
$nonsequential = Array (1=> "foo", 2=> "bar", 3=> "Baz", 4=> "Blong");
Var_dump (
$nonsequential,
Json_encode ($nonsequential)
);

echo Php_eol. " Deletes a contiguous array of values resulting from a continuous array. Php_eol;
Unset ($sequential [1]);
Var_dump (
$sequential,
Json_encode ($sequential)
);
?>

The above routines will output:
Copy Code code as follows:

Contiguous array
Array (4) {
[0]=>
String (3) "Foo"
[1]=>
String (3) "Bar"
[2]=>
String (3) "Baz"
[3]=>
String (5) "Blong"
}
string ["foo", "Bar", "Baz", "Blong"] "

Non-contiguous arrays
Array (4) {
[1]=>
String (3) "Foo"
[2]=>
String (3) "Bar"
[3]=>
String (3) "Baz"
[4]=>
String (5) "Blong"
}
String (1): "foo", "2": "Bar", "3": "Baz", "4": "Blong"} "

A discontinuous array that is generated by deleting a contiguous array value
Array (3) {
[0]=>
String (3) "Foo"
[2]=>
String (3) "Baz"
[3]=>
String (5) "Blong"
}
String "{0": "foo", "2": "Baz", "3": "Blong"} "

Copy Code code as follows:

$obj->name= ' A1 '; $obj->number = ' 123 ';
$obj->contno= ' 000 ';
echo Json_encode ($obj);

The results are:
Copy Code code as follows:

{' Name ': ' A1 ',
"Number": "123",
"Contno": "000"
}

You can see that Json_encode () and Json_decode () are compile and decompile, and note that JSON only accepts UTF-8 encoded characters, so the argument for Json_encode () must be utf-8 encoded, or it will get null characters or NULL.

PS: This site also provides several powerful JSON parsing, conversion and formatting tools for everyone to choose to use, I believe that the next JSON Format data processing will help:

Online JSON code inspection, inspection, landscaping, formatting tools:
Http://tools.jb51.net/code/json

Online Xml/json Convert to each other:
Http://tools.jb51.net/code/xmljson

JSON code online Format/beautify/compress/edit/Convert tools:
Http://tools.jb51.net/code/jsoncodeformat

C Language Style/html/css/json code formatting landscaping Tools:
Http://tools.jb51.net/code/ccode_html_css_json

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.