Home Backend Development PHP Tutorial Compare the differences between json_encode and json_decode

Compare the differences between json_encode and json_decode

Jul 20, 2017 pm 05:22 PM
decode encode javascript

Four basic principles of JSON

1) Parallel data are separated by commas (,)
2) Mapping is represented by (":") colon
3) The collection (data) of parallel data is represented by square brackets ("[]")
4) The mapped collection (object) is represented by curly brackets ("{}")

1.json_decode()

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

json_decode — Characters in JSON format String encoding

Description
mixed json_decode (string $json [, bool $assoc])
Accepts a JSON format string and converts it into a PHP variable

Parameters

json
The string in json string format to be decoded.

assoc
When this parameter is TRUE, array will be returned instead of object.


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

Example

Example #1 json_decode Example of ()

Copy the code as follows:


$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 the 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 the code code 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);


The result is:

Copy the code 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 objects compiled by json_decode() are now output as json_decode ($data,true) Try

Copy the code as follows:


echo json_decode($data,true);


Result:

Copy the code code 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] => ) )


It can be seen that json_decode($data,true) outputs an associative array. It can be seen that json_decode($data) outputs 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 the variable Encoding

Report a bug Description
string json_encode (mixed $value [, int $options = 0 ] )
Return the JSON form of value

Report a bug Parameters

value
The value to be encoded can be any data type except resource type

This function can only accept UTF-8 encoded data

options
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
Encoding If successful, a JSON format is returned. Represents a string or returns FALSE on failure.

Report a bug Update log
Version Description
5.4.0 options parameter constants added: JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, and JSON_UNESCAPED_UNICODE.
5.3.3 The options parameter adds a constant: JSON_NUMERIC_CHECK.
5.3.0 Add options parameter.


Report a bug Example

Example #1 A json_encode() example

Copy code code as follows:


$arr ​​= array ('a'=>1,'b'=>2,'c'=>3,'d'=>4, 'e'=>5);

echo json_encode($arr);
?>


The above routine will output:

Copy code The code is as follows:


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


Example #2 Usage of options parameter in json_encode() function

Copy the code The code is as follows:


$a = array('',"'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\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\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\ 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\n";
?>


The above routine will output:

Copy the code as follows:


Normal: [""," 'bar'","\"baz\"","&blong&","\u00e9"]
Tags: ["\u003Cfoo\u003E","'bar'","\"baz\""," &blong&","\u00e9"]
Apos: ["","\u0027bar\u0027","\"baz\"","&blong&","\u00e9"]
Quot: ["","'bar'","\u0022baz\u0022","&blong&","\u00e9"]
Amp: ["","'bar'"," \"baz\"","\u0026blong\u0026","\u00e9"]
Unicode: ["","'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 Continuous and Non-consecutive array example

Copy the code as follows:


echo "Continuous array".PHP_EOL;
$sequential = array( "foo", "bar", "baz", "blong");
var_dump(
$sequential,
json_encode($sequential)
);

echo PHP_EOL. "Nonsequential array".PHP_EOL;
$nonsequential = array(1=>"foo", 2=>"bar", 3=>"baz", 4=>"blong");
var_dump(
$nonsequential,
json_encode($nonsequential)
);

echo PHP_EOL."A non-continuous 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 the code code 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"}"

A non-continuous array generated by deleting 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 the code as follows:


$obj->Name= 'a1';$obj->Number ='123';
$obj->Contno= '000';
echo json_encode($obj);


The result is:

Copy the code as follows:


{" Name":"a1",
"Number":"123",
"Contno":"000"
}


You can see json_encode() and json_decode() are the compilation and decompilation process. Note that json only accepts utf-8 encoded characters, so the parameters of json_encode() must be utf-8 encoded, otherwise you will get empty characters or null.


json
The string in json string format to be decoded.

assoc
When this parameter is TRUE, array will be returned instead of object.


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

Example

Example #1 json_decode Example of ()

Copy the code as follows:


$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 the 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 the code The 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);


The result is:

Copy the code 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 try to output json_decode($data,true)

Copy the code as follows:


echo json_decode($data,true);


Result:

Copy the code 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] => ) )


It can be seen that json_decode($data,true) outputs an associative array. From this, it can be seen that json_decode($data) outputs 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 — Yes Variables are JSON encoded

Report a bug Description
string json_encode (mixed $value [, int $options = 0 ] )
Return the JSON form of value

Report a bug Parameters

value
The value to be encoded can be any data type except the resource type

This function can only accept UTF-8 encoded data

options
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
If encoding is successful, return one A string represented as JSON or FALSE on failure.

Report a bug Update log
Version Description
5.4.0 options parameter constants added: JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, and JSON_UNESCAPED_UNICODE.
5.3.3 The options parameter adds a constant: JSON_NUMERIC_CHECK.
5.3.0 Add options parameter.


Report a bug Example

Example #1 A json_encode() example

Copy the code as follows:


$arr ​​= array ('a'=>1,'b'=>2,'c'=>3,'d'=> 4,'e'=>5);

echo json_encode($arr);
?>


The above routine will output:

Copy code The code is as follows:


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


Example #2 Usage of options parameter in json_encode() function

Copy the code as follows:


$a = array(' ',"'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"; #$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\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\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\n";
?>


The above routine Will output:

Copy the code code as follows:


Normal: ["","'bar'","\"baz\"","&blong&","\u00e9"]
Tags: ["\u003Cfoo\u003E ","'bar'","\"baz\"","&blong&","\u00e9"]
Apos: ["","\u0027bar\u0027","\"baz\ "","&blong&","\u00e9"]
Quot: ["","'bar'","\u0022baz\u0022","&blong&","\u00e9"]
Amp: ["","'bar'","\"baz\"","\u0026blong\u0026","\u00e9"]
Unicode: [""," '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 Example of continuous and non-continuous arrays

Copy the code as follows:


echo "Continuous Array" .PHP_EOL;
$sequential = array("foo", "bar", "baz", "blong");
var_dump(
$sequential,
json_encode($sequential)
);

echo PHP_EOL."Nonsequential array".PHP_EOL;
$nonsequential = array(1=>"foo", 2=>"bar", 3=>"baz" , 4=>"blong");
var_dump(
$nonsequential,
json_encode($nonsequential)
);

echo PHP_EOL."Delete a continuous array value Non-continuous array generated by ".PHP_EOL;
unset($sequential[1]);
var_dump(
$sequential,
json_encode($sequential)
);
? >


The above routine will output:

Copy the code 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"}"

Delete one A non-continuous array generated by the method of continuous array values ​​
array(3) {
[0]=>
string(3) "foo"
[2]=>
string (3) "baz"
[3]=>
string(5) "blong"
}
string(33) "{"0":"foo","2": "baz","3":"blong"}"


Copy the code. The code is as follows:


$obj->Name= 'a1'; $obj->Number ='123';
$obj->Contno= '000';
echo json_encode($obj);


The result is:

Copy the code 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 encoded characters, so the parameters of json_encode() must be utf-8 encoded. , otherwise you will get an empty character or null.

The above is the detailed content of Compare the differences between json_encode and json_decode. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Advanced usage and skill sharing of Oracle DECODE function Advanced usage and skill sharing of Oracle DECODE function Mar 08, 2024 am 10:30 AM

The DECODE function in Oracle database is a very commonly used function, which can select among a set of values ​​based on the result value of an expression. The syntax of the DECODE function is as follows: DECODE(expression, search_value1, result1, search_value2, result2,..., default_result) where expression is the expression to be compared, s

Oracle DECODE function detailed explanation and usage examples Oracle DECODE function detailed explanation and usage examples Mar 08, 2024 pm 03:51 PM

The DECODE function in Oracle is a conditional expression that is often used to return different results based on different conditions in query statements. This article will introduce the syntax, usage and sample code of the DECODE function in detail. 1. DECODE function syntax DECODE(expr,search1,result1[,search2,result2,...,default]) expr: the expression or field to be compared. search1,

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles