This example describes a workaround for PHP to handle JSON string decoding to return null. Share for everyone to use for reference. The specific methods are as follows:
In general,PHP uses the Json_decode () function for JSON string decoding, the first parameter passes a string, and the second argument is true, returns an array, or, if False, returns object. If NULL is returned, the error is indicated, output json_last_error (), and the resulting integer value corresponds to the wrong hint . As shown in the following illustration:
Json_last_error () is more common than integer 4, which is that the JSON string was incomplete before Json_decode, so the syntax is wrong.
Then must be the client submitted individual characters affect the format of JSON, you can use JS filter, you can solve general problems, the main filter return, spaces, HTML tags.
The implementation code is as follows:
/
* Filter functions/function
htmlEncode (str) {
str = str.replace (/\s+/ig, ');
str = str.replace (/&/g, "");
str = str.replace (/</g, "");
str = str.replace (/>/g, "");
str = str.replace (/(?: t| |v|r) *n/g, ' <br/> ');
str = str.replace (/t/g, "");
str = str.replace (/x22/g, ' "");
str = str.replace (/x27/g, "");
str = str.replace (/"/g," ");
return str;
}
The above situation is that you have to submit JSON string data to server processing, which can only be filtered on the client side.
Some of the reasons why other Json_decode ($STR) return null:
1. $str can only UTF-8 code
2. Element can not have a comma at the end (unlike the PHP array)
3. Elements cannot use single quotes
4. Element values cannot have spaces in between and \ n, must be replaced
If you encounter the above situation, you can follow the above methods to deal with.
PS: About JSON operation, here we recommend a few more practical JSON online tools for your reference to use:
Online JSON code inspection, inspection, landscaping, formatting tools:
Http://tools.jb51.net/code/json
JSON Online formatting tool:
Http://tools.jb51.net/code/jsonformat
Online Xml/json Mutual Conversion tool:
Http://tools.jb51.net/code/xmljson
JSON code online Format/beautify/compress/edit/Convert tools:
Http://tools.jb51.net/code/jsoncodeformat
Online JSON compression/escape tool:
Http://tools.jb51.net/code/json_yasuo_trans
C Language Style/html/css/json code formatting landscaping Tools:
Http://tools.jb51.net/code/ccode_html_css_json
I hope this article will help you with your PHP program design.