Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the functions related to JSON in PHP

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail the functions related to JSON in PHP. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

In the days when we just went to work, it was all dominated by XML, but now JSON data format is the de facto standard for transmission in various applications. Students who have started learning programming and development in recent years may not have been exposed to using XML for data transfer at all. Of course, the times are advancing all the time. Compared with XML, JSON is more convenient, faster and more readable. But in fact, from a semantic point of view, the form of expression of XML is stronger.

Needless to say, operating JSON in PHP is actually very simple, and the most commonly used functions are json_encode () and json_decode (). They have some places to pay attention to, but also some interesting places.

JSON coding

First, we prepare an array for the operation that we code later.

$data = ['id' = > 1,' name' = > 'Test situation', 'cat' = > [' Student &'on the job',], 'number' = > "123123123",' edu' = > [['name' = >' Middle School', 'date' = >' 2015-2018',], ['name' = >' University' 'date' = >' 2018-2022,]

Very simple array, in fact, there is nothing special, just the nesting of data, there are some Chinese and special symbols. For normal JSON coding, you can simply use json_encode ().

$json1 = json_encode ($data); var_dump ($json1) / / string (215) "{" id ": 1," name ":"\ u6d4b\ u8bd5\ u60c5\ u51b5 "," cat ": ["\ u5b66\ u751f &\ "u5728\ u804c\"], "number": "123123123", "edu": [{"name": "\ u4e2d\ u5b66", "date": "2015-2018"}, {"name": "\ u5927\ u5b66", "date": "2018-2022"}} "Chinese processing"

Did you find anything wrong with the encoded JSON data above? Yes, I believe many people will see at a glance that all Chinese characters have been converted to the format\ uxxxx. This is actually that by default, the json_encode () function converts these multi-byte characters into Unicode format. We can solve this problem by adding a constant parameter directly after json_encode (), so that the Chinese characters are displayed normally.

$json1 = json_encode ($data, JSON_UNESCAPED_UNICODE); var_dump ($json1); / / string (179) "{" id ": 1," name ":" Test situation "," cat ": [" Student &\ "on the job\"], "number": "123123123", "edu": [{"name": "Middle School", "date": "2015-2018"}, {"name": "University", "date": "2018-2022"}]} "

Of course, it's just so boring. Because an interviewer once asked me during an interview that if I solved this problem, I wouldn't use this constant parameter. Can you think about what solution you have without looking at the code below?

Function t ($data) {foreach ($data as $k = > $d) {if (is_object ($d)) {$d = (array) $d;} if (is_array ($d)) {$data [$k] = t ($d);} else {$data [$k] = urlencode ($d);}} return $data;} $newData = t ($data) $json1 = json_encode ($newData); var_dump (urldecode ($json1)); / / string (177) "{" id ":" 1 "," name ":" Test situation "," cat ": [" Student & "on the job"], "number": "123123123", "edu": [{"name": "Middle School", "date": "2015-2018"}, {"name": "University", "date": "2018-2022"}]} "

In fact, it is a very simple solution that recursively converts the contents of all the fields in the data into urlencode () encoding, then uses json_encode () encoding, and then uses urldecode () to solve it. Isn't that interesting? In fact, this is a little trick of many old programmers, because the constant JSON_UNESCAPED_UNICODE is available only after PHP5.4, so if you want the encoded data to be displayed directly in Chinese, you can only do so.

Of course, it is now the era of PHP8, and it is no longer necessary to operate in such a troublesome way, but we can't rule out the possibility that some interview libraries deliberately ask such questions because they are old farmers. Just know that there is such a thing, after all, in the actual project development, the use of PHP5.4 version of the system may be very few (such a company does not go, the technology update is too slow).

Other parameters

In addition to JSON_UNESCAPED_UNICODE, we have many constant parameters that can be used, and this parameter can be operated in parallel, that is, multiple constant parameters can work together.

$json1 = json_encode ($data, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_NUMERIC_CHECK | JSON_HEX_QUOT); var_dump ($json1) / / string "{" id ": 1," name ":" Test situation "," cat ": [" Student\ u0026\ u0022 on the job\ u0022 "]," number ": 123123123," edu ": [{" name ":" u003Cb\ u003E Middle School\ u003C\ / b\ u003E "," date ":" 2015-2018 "}, {" name ":"\ u003Cb\ u003E University\ u003C\ / b\ u003E "," date ":" 2018-2022 "}]}"

This pile of parameters is actually aimed at some special symbols in our data, such as & symbols, HTML tags, and so on. Of course, there are some constant parameters that have not been fully shown, so you can refer to the instructions in the official manual.

In addition, json_encode () has a third parameter, which represents the level of iteration. For example, the data above us is a multi-dimensional array, it has three layers, so we have to give at least 3 to parse normally. In the following code, we just give a 1, so the returned content is false. That is, it cannot be coded successfully. By default, the value of this parameter is 512.

Var_dump (json_encode ($data, JSON_UNESCAPED_UNICODE, 1)); / / bool (false) object and format processing

By default, json_encode () encodes according to the type of data, so if it is an array, then its encoded content is the array format of JSON, and we can also add a JSON_FORCE_OBJECT to encode an array in the form of an object.

$data = []; var_dump (json_encode ($data)); / / string (2) "[]" var_dump (json_encode ($data, JSON_FORCE_OBJECT)); / / string (2) "{}"

We have learned before when talking about mathematical related functions that json_encode () cannot be encoded if there is NAN in the data. In fact, we can add a JSON_PARTIAL_OUTPUT_ON_ERROR to replace some non-coding values. In the following code, we can use it to replace NAN with 0.

$data = NAN;var_dump (json_encode ($data)); / / bool (false) var_dump (json_encode ($data, JSON_PARTIAL_OUTPUT_ON_ERROR)); / / 0 object encoding attribute problem

For an object, the JSON-encoded content is just like serialization, with only the object's properties and no methods. After all, the greatest use of JSON is for data transmission, and the method has no practical effect on data transmission. The attribute will also vary according to its encapsulation, and will only encode the public, that is, the public attribute.

$data = new class {private $a = 1; protected $b = 2; public $c = 3; public function x () {}}; var_dump (json_encode ($data)); / / string (7) "{" c ": 3}"

As you can see from this test code, the protected, private properties, and that method are not encoded.

JSON decoding

It's actually easier for JSON decoding because json_decode () doesn't have that many constant parameters.

Var_dump (json_decode ($json1)); / / object (stdClass) # 1 (5) {/ / ["id"] = > / / int (1) / / ["name"] = > / / string (12) "Test status" / / ["cat"] = > / /. / /. Var_dump (json_decode ($json1, true)); / / array (5) {/ / ["id"] = > / / int (1) / / ["name"] = > / / string (12) "Test status" / / ["cat"] = > / /. / /.

First of all, let's look at its second parameter. The role of this parameter can be seen in the code. If this parameter is left unfilled, that is, by default, its value is false, then the decoded data is in object format. If we set this parameter to true, the decoded result will be in array format. This is also a very common function, so we don't have to explain it any more.

Var_dump ('{"a": 132123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123

For data in this very long digital format, if it is decoded directly by json_decode (), it will be converted directly to scientific counting. We can directly use a JSON_BIGINT_AS_STRING constant parameter to convert this data into a string when decoding, which means that the original appearance of the data is preserved. Note that the parameter of the json_decode () function has four parameters, the third is the iteration depth, and the fourth is the definition of these formatted constant values, because there is a parameter that converts the object to an array. And it and json_encode () is the opposite, iterative depth parameter before, format constant parameter after, we must pay attention to here!

If the data is incorrect, json_decode () returns NULL.

Var_dump (json_decode (", true)); / / NULLvar_dump (json_decode (" {avell} ", true)); / / NULL error handling

In the above two pieces of code, we have demonstrated what happens if there is a problem with the encoded or decoded data, such as json_encode () returns false and json_decode () returns NULL. But what's the specific reason?

Data = NAN;var_dump (json_encode ($data)); / / bool (false) var_dump (json_last_error ()); / / int (7) var_dump (json_last_error_msg ()); / / string (34) "Inf and NaN cannot be JSON encoded"

Yes, json_last_error () and json_last_error_msg () return the error message of the JSON operation. In other words, json_encode () and json_decode () do not report errors under normal circumstances, and if we want to get the error message, we have to use these two functions to get. This is also a lot of novice students did not pay attention to, no error information, do not throw abnormal problems to our development and debugging is actually very unfriendly. Because I probably didn't know what the problem was after looking for it for a long time.

After PHP7.3, a new constant parameter has been added to allow our json_encode () and json_decode () to throw an exception when coding / decoding errors, so that we can quickly locate the problem. Now, if your system environment is above PHP7.3, it is highly recommended to use this constant parameter to allow the system to throw an exception.

/ / php7.3var_dump (json_encode ($data, JSON_THROW_ON_ERROR)); / / Fatal error: Uncaught JsonException: Inf and NaN cannot be JSON encodedvar_dump (json_decode (', true, 512, JSON_THROW_ON_ERROR)); / / PHP Fatal error: Uncaught JsonException: Syntax error

JSON_THROW_ON_ERROR works for both json_encode () and json_decode (). Similarly, as long as this constant parameter is set, we can use try...catch to capture.

Try {var_dump (json_encode ($data, JSON_THROW_ON_ERROR));} catch (JsonException $e) {var_dump ($e-> getMessage ()); / / string (34) "Inf and NaN cannot be JSON encoded"} JSON serialization interface

In the previous article, we learned to use the Serializable interface to customize the serialization of classes in PHP. In other words, we can customize the serialized format content through the Serializable interface. For JSON, a JsonSerializable interface is also provided to implement the object format content when I customize the JSON encoding.

Class jsontest implements JsonSerializable {public function _ construct ($value) {$this- > value = $value;} public function jsonSerialize () {return $this- > value;}} print "Null->". Json_encode (new jsontest (null)). \ n "; print" Array-> ". Json_encode (new jsontest (array (1,2,3). "\ n"; print "Assoc.->" Json_encode (array ('a'= > 1,'b' = > 3,'c'= > 4)). \ n "; print" Int-> ". Json_encode (new jsontest (5)) \ n "; print" String-> ". Json_encode (new jsontest ('Hello, Worldwide')). \ n "; print" Object-> ". Json_encode (new jsontest ((object) array ('a'= > 1,'b' = > 3,'c'= > 4). "\ n"; / / Null-> null// Array-> [1, Assoc 2, 3] /. -> {"a": 1, "b": 3, "c": 4} / / Int-> 5 String-> "Hello, World!" / / Object-> {"a": 1, "b": 3, "c": 4}

This is a small example, you only need to implement the jsonSerialize () method in the JsonSerializable interface and return the contents to specify the JSON encoding format of the jsontest object. Here we simply return the contents of the data, which is not much different from the normal json_encode (). Let's take a look at it through a complex example.

Class Student implements JsonSerializable {private $id; private $name; private $cat; private $number; private $edu; public function _ _ construct ($id, $name, $cat = null, $number = null, $edu = null) {$this- > id = $id; $this- > name = $name; $this- > cat = $cat; $this- > number = $number; $this- > edu = $edu } public function jsonSerialize () {if (! $cat) {$this- > cat = ['student'];} if (! $edu) {$this- > edu = new stdClass;} $this- > number = 'student ID:'. (! $number? Mt_rand (): $number); if ($this- > id = = 2) {return [$this- > id, $this- > name, $this- > cat, $this- > number, $this- > edu,] } return ['id' = > $this- > id,' name' = > $this- > name, 'cat' = > $this- > cat,' number' = > $this- > number, 'edu' = > $this- > edu,];} var_dump (json_encode (new Student (1,' Test 1'), JSON_UNESCAPED_UNICODE)) / string (82) "{" id ": 1," name ":" Test one "," cat ": [" Student "]," number ":" Student number: 14017495 "," edu ": {}" var_dump ([new Student (1, 'Test 1'), new Student (2, 'Test 2')], JSON_UNESCAPED_UNICODE) / string "[{" id ": 1," name ":" Test one "," cat ": [" Student "]," number ":" Student number: 1713936069 "," edu ": {}, [2," Test II ", [" Student "]," Student number: 499173036 ", {}]]"

In this example, we did something in jsonSerialize (). If the data does not pass a value, such as in the case of null, give a default value. Then return a normal array with an id of 2. You can see the format of the second piece of data in the last paragraph of the comment.

This interface is not very interesting, I believe you may be very familiar with the above json_encode () and json_decode (), but this interface is estimated that many people really have not touched, is not very interesting.

This is the end of this article on "what are the functions related to JSON in PHP?". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report