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

Source: Internet
Author: User

Json_decode encoding the JSON-formatted string and json_encode the variable json, the required friend can refer to the following

1.json_decode ()

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

json_decode-encoding a JSON-formatted string

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

Parameters

Json
String in JSON string format to decode.

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


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

Example

Examples of Example #1 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 example above 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 ': ', ' ' qqno ': '},{' Name ': ' A1 ', ' Number ': ' 123 ', ' Contno ': ' $ ', ' qqno ":" "},{" Name ":" A1 "," Number ":" 123 "," Contno ":" The "," Qqno ":"}] ';
echo Json_decode ($data);

The result is:
Copy CodeThe code is 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 (), and now output Json_decode ($data, true) try
Copy CodeThe code is as follows:
Echo Json_decode ($data, true);

Results:
Copy CodeThe code is 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] =&gt ; [qqno] =))

You can see an associative array of Json_decode ($data, true) output, so Json_decode ($data) outputs an object, and Json_decode ("$arr", true) is forcing 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 variables

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

Report a bug parameter

Value
The value to encode, 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.

Report a bug return value
A successful encoding returns a string in JSON form or FALSE on failure.

Report a Bug update log
Release Notes
5.4.0 Options parameter 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.


Report a bug Example

Example #1 a json_encode () example
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 routines will output:
Copy CodeThe code is 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 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 (array (all));

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 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: [[[+]]
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 continuous and discontinuous arrays example
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. " 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 in a way that produces a non-contiguous array ". Php_eol;
Unset ($sequential [1]);
Var_dump (
$sequential,
Json_encode ($sequential)
);
?>

The above routines will output:
Copy CodeThe code is 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 array
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 "}"

Non-contiguous array produced by deleting a continuous array of values
Array (3) {
[0]=>
String (3) "Foo"
[2]=>
String (3) "Baz"
[3]=>
String (5) "Blong"
}
String "{" 0 ":" foo "," 2 ":" Baz "," 3 ":" Blong "}"

Copy CodeThe code is as follows:
$obj->name= ' A1 '; $obj->number = ' 123 ';
$obj->contno= ' 000 ';
echo Json_encode ($obj);

The result is:
Copy CodeThe code is as follows:
{"Name": "A1",
"Number": "123",
"Contno": "000"
}

As you can see, Json_encode () and Json_decode () are compiled and deserialized, and note that JSON only accepts UTF-8 encoded characters, so the parameters of Json_encode () must be utf-8 encoded, otherwise they will be null or empty.

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

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.