search
HomeBackend DevelopmentPHP ProblemWhat to do if php json_decode parsing fails

php Solution to json_decode parsing failure: 1. Obtain the error code through json_last_error and other functions; 2. Eliminate illegal utf8 characters according to the utf8 encoding range.

What to do if php json_decode parsing fails

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

php json_decode parsing failure manage?

php json_decode parsing failure and error handling

Under normal circumstances, after obtaining a piece of json content, directly json_decode($content, true) is converted into an array Come and use it, it’s very convenient.
However, if there is something wrong with the interface that provides you with json content, and the json provided is not standard or simply has errors, then you have to find a way to find the problem.
Let’s take a look at the manul of json_encode first
https://www.php.net/manual/en/function.json-last-error.php

Returns NULL on failure

 //  $json = '{"a":1,"b":2,"c":3,"d":4,"e":5, "name":"Corwien"}'; 
 $json = '{"a":1,"b":2,"c":3,"d":4,"e":5, "name":}';  //错误的json格式
 $result = json_decode($json, true);
  if(!$result)
  {
        //error handle ,错误处理
        $ret = json_last_error();
        print_r($ret);   //打印为: 4,查错误信息表,可知是语法错误
        
  }   

json_last_error错误msg对照表:
0 = JSON_ERROR_NONE
1 = JSON_ERROR_DEPTH
2 = JSON_ERROR_STATE_MISMATCH
3 = JSON_ERROR_CTRL_CHAR
4 = JSON_ERROR_SYNTAX
5 = JSON_ERROR_UTF8

How do we know where we went wrong?

1. Get the error code

php has a json_last_error function, see
https://www.php.net/manual/en/function.json -last-error.php

It will return an error code to tell us what went wrong.
Can’t understand the error code? You can use json_last_error_msg, see
https://www.php.net/manual/en/function.json-last-error-msg.php

But json_last_error_msg is only available in php >= 5.5.0 It only exists in different versions. If the version is lower, just define one yourself.

2. The lower version of php json error codes are incomplete

However, if you pay attention to the manual, you will find that many of the error codes defined in json_last_error are only available in the higher version. Yes, lower versions of php are out of service. For example, the JSON_ERROR_UTF8 error code clearly tells us that there are illegal utf8 characters in the json string, but it only exists in Php >= 5.3.3. The tragedy is that my php is 5.3.2....

所以,如果你的json_last_error返回的是JSON_ERROR_NONE(0) ,并不是说没有错误,而只是这个错误在你的低版本php中没有定义。再说,没有错误怎么会失败呢....

If the json format is wrong, no matter how low the version of php is, it will tell you JSON_ERROR_SYNTAX, so the first possibility is JSON_ERROR_NONE. Think about illegal utf8 strings.

3. How to deal with illegal utf8 characters in json

According to the encoding range of utf8, illegal utf8 characters can be eliminated.
See https://magp.ie/2011/01/06/remove-non-utf8-characters-from-string-with-php/

//reject overly long 2 byte sequences, as well as characters above U+10000 and replace with ?
$some_string = preg_replace('/[\x00-\x08\x10\x0B\x0C\x0E-\x19\x7F]'.
 '|[\x00-\x7F][\x80-\xBF]+'.
 '|([\xC0\xC1]|[\xF0-\xFF])[\x80-\xBF]*'.
 '|[\xC2-\xDF]((?![\x80-\xBF])|[\x80-\xBF]{2,})'.
 '|[\xE0-\xEF](([\x80-\xBF](?![\x80-\xBF]))|(?![\x80-\xBF]{2})|[\x80-\xBF]{3,})/S',
 '?', $some_string );
 
//reject overly long 3 byte sequences and UTF-16 surrogates and replace with ?
$some_string = preg_replace('/\xE0[\x80-\x9F][\x80-\xBF]'.
 '|\xED[\xA0-\xBF][\x80-\xBF]/S','?', $some_string );

Here are the illegal characters replaced with? , change it yourself as needed.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of What to do if php json_decode parsing fails. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)