"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why does `json_decode` return NULL, although JSON data looks valid?

Why does `json_decode` return NULL, although JSON data looks valid?

Posted on 2025-04-13
Browse:155

Why Does `json_decode` Return NULL Despite Valid-Looking JSON Data?

Understanding JSON Decoding Issue in Web Service Calls

In web service interactions, occasionally, the json_decode function returns NULL. A confounding issue arises when a web service provides JSON data that resembles:

var_dump($foo):
string(62) "{"action":"set","user":"123123123123","status":"OK"}"

However, attempting to decode the JSON in the application returns NULL:

$data = json_decode($foo, true);
var_dump($data):
NULL

Resolving the Problem

One potential cause for this issue is PHP's magic quotes functionality. Magic quotes automatically escape special characters in form data, potentially interfering with JSON parsing. To resolve this:

if (get_magic_quotes_gpc()) {
  $param = stripslashes($_POST['param']);
} else {
  $param = $_POST['param'];
}
$param = json_decode($param, true);

By disabling magic quotes or stripping slashes from the JSON data, the application can accurately decode the JSON and retrieve the desired information.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3