php json_decode() 返回空问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3110487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
json_decode() returns null issues
提问by Matt
I've an issue with my JSON. It works returns correctly in PHP 5.3 (so I can't use json_last_error()), and it returns successfully when I copy string explicitly into json_decode (json_decode('{...}'). It only returns null in when I pass the result as a variable and I'm using php 5.2, which is what I need it for.
我的 JSON 有问题。它在 PHP 5.3 中正常返回(所以我不能使用 json_last_error()),并且当我将字符串显式复制到 json_decode (json_decode('{...}') 时它成功返回。它只在我通过时返回 null结果作为变量,我使用的是 php 5.2,这正是我需要的。
The output comes from JSON logging in PHPUnit:
输出来自 PHPUnit 中的 JSON 日志记录:
[
{
"event": "suiteStart",
"suite": "",
"tests": 2
},
{
"event": "suiteStart",
"suite": "TagTestCase",
"tests": 2
},
{
"event": "test",
"suite": "TagTestCase",
"test": "TagTestCase::test_it",
"status": "fail",
"time": 0.00248718261719,
"trace": [
{
"file": "\/UnitTest\/PHPUnit.php",
"line": 98,
"function": "run",
"class": "PHPUnit_Framework_TestSuite",
"type": "->",
"args": [
{
}
]
},
{
"file": "\/UnitTest\/PHPUnit.php",
"line": 116,
"function": "run",
"class": "PHPUnit",
"type": "->",
"args": [
]
},
{
"file": "\/UnitTest\/PHPUnit.php",
"line": 212,
"function": "__tostring",
"class": "PHPUnit",
"type": "->",
"args": [
]
}
],
"message": "false assertionzzzzz.\nFailed asserting that <boolean:false> is true."
},
{
"event": "test",
"suite": "TagTestCase",
"test": "TagTestCase::test_two",
"status": "pass",
"time": 0.00182914733887,
"trace": [
],
"message": ""
}
]
EDIT: These are the paths, I've been exploring - maybe you are a better explorer.. Three possible paths that could help:
编辑:这些是路径,我一直在探索 - 也许你是一个更好的探索者......可能有帮助的三个可能的路径:
- What is different about json_decode() in php 5.2 then 5.3? what did they change?
- Someone else using JSON from PHPUnit, and how they parse it.
- What changes when you have it in a variable vs. printing it to screen and copying it into json_decode()
- php 5.2 和 5.3 中的 json_decode() 有什么不同?他们改变了什么?
- 其他人使用来自 PHPUnit 的 JSON,以及他们如何解析它。
- 将它放在变量中与将其打印到屏幕并将其复制到 json_decode() 中时会发生什么变化
Any help would be greatly(!) appreciated.
任何帮助将不胜感激。
Thanks! Matt
谢谢!马特
回答by Matt
What a HORRENDOUS debug session.. well there's good news.. I figured it out..
多么可怕的调试会话.. 好消息.. 我想通了..
I started looking at it using AJAX and logging it with Firebug... and it turns out json_decode (or eval by the way) cannot handle ", which is what PHPUnit sends back (Come on Sebastian!), so to fix it:
我开始使用 AJAX 查看它并使用 Firebug 记录它......结果是 json_decode(或 eval 顺便说一下)无法处理",这是 PHPUnit 发回的内容(来吧塞巴斯蒂安!),所以要修复它:
$json = str_replace('"', '"', $json);
Now I thought they were the same.. maybe someone can enlighten me..
现在我以为他们是一样的..也许有人可以启发我..
回答by Matija
Yesterday I spent 2 hours on checking and fixing that error finally I found that in JSON string that I wanted to decode were '\' slashes. So the logical thing to do is to use stripslashes function or something similiar to different PL.
昨天我花了 2 个小时检查并修复该错误,最后我发现在 JSON 字符串中我想解码的是 '\' 斜杠。所以合乎逻辑的做法是使用stripslashes函数或类似不同PL的东西。
Of course the best way is sill to print this var out and see what it becomes after json_decode, if it is null you can also use json_last_error()function to determine the error it will return integer but here are those int described:
当然,最好的方法是打印这个 var 并查看它在 json_decode 之后变成什么,如果它是 null,你也可以使用json_last_error()函数来确定它将返回整数的错误,但这里是那些 int 描述:
0 = JSON_ERROR_NONE
0 = JSON_ERROR_NONE
1 = JSON_ERROR_DEPTH
1 = JSON_ERROR_DEPTH
2 = JSON_ERROR_STATE_MISMATCH
2 = JSON_ERROR_STATE_MISMATCH
3 = JSON_ERROR_CTRL_CHAR
3 = JSON_ERROR_CTRL_CHAR
4 = JSON_ERROR_SYNTAX
4 = JSON_ERROR_SYNTAX
5 = JSON_ERROR_UTF8
5 = JSON_ERROR_UTF8
In my case I got output of json_last_error() as number 4so it is JSON_ERROR_SYNTAX. Then I went and take a look into the string it self which I wanted to convert and it had in last line:
在我的例子中,我得到的 json_last_error() 输出为4,所以它是JSON_ERROR_SYNTAX。然后我去看看我想转换的字符串它自己,它在最后一行:
'\'title\' error ...'
After that is really just an easy fix.
在那之后真的只是一个简单的修复。
$json = json_decode(stripslashes($response));
if (json_last_error() == 0) { // you've got an object in $json}
回答by Keith Minkler
When I use:
当我使用:
phpunit --log-json file.json <test_file>
(using PHPUnit 3.4.13), The file that it creates does not appear to contain valid JSON,
(使用 PHPUnit 3.4.13),它创建的文件似乎不包含有效的 JSON,
the json file contains "json" which looks something like:
json 文件包含“json”,类似于:
{...}{...}{...}{...}
Instead of what I would expect to see:
而不是我期望看到的:
[{...},{...},{...},{...}]
Not sure if the is the same problem that you're seeing, your sample JSON output in the question appears to be more valid that what I'm seeing.
不确定这是否与您所看到的问题相同,问题中的示例 JSON 输出似乎比我所看到的更有效。
Once adding the missing commas and brackets, it can be parsed with json_decode() on PHP 5.2.10 or PHP 5.3.2.
添加缺少的逗号和括号后,可以在 PHP 5.2.10 或 PHP 5.3.2 上使用 json_decode() 对其进行解析。
回答by Samuel Kwame Antwi
Try this the problem is this html_entity_decode($your value);
试试这个问题是这个 html_entity_decode($your value);
if(get_magic_quotes_gpc()){
$param = stripslashes($row['your column name']);
}else{
$param = $row['your column name'];
}
$param = json_decode(html_entity_decode($param),true);
$json_errors = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
);
echo 'Last error : ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;
print_r($param);
回答by Balibia
You should use this
你应该用这个
$jsonstring = stripslashes(str_replace('\"', '"', $jsonstring));
I tested this with PHP 5.3
我用 PHP 5.3 对此进行了测试
回答by dtar
Since PHP 7.3, the json_decode function will accept a new JSON_THROW_ON_ERROR option that will let json_decode throw an exception instead of returning null on error.
自 PHP 7.3 起, json_decode 函数将接受一个新的 JSON_THROW_ON_ERROR 选项,该选项将使 json_decode 抛出异常而不是在出错时返回 null。
Example:
例子:
try {
json_decode("{", false, 512, JSON_THROW_ON_ERROR);
}
catch (\JsonException $exception) {
echo $exception->getMessage(); // displays "Syntax error"
}
回答by jQuery
You can set the database charset before submitting - solved issues on my end:
您可以在提交之前设置数据库字符集 - 解决了我的问题:
$sql = $mysqli->set_charset("utf8");
回答by user3633397
I notice this behavior with PHP version 5.14.12, and it may be for others versions as well.
When using file_get_contents to load a JSON string into json_decode function, I had to strip out the BOM characters i.e. for UTF-8 EF BB BF before it would work properly.
Compare the lengths of your two strings --the hard coded versus the passed in variable-- if they are not the same, these characters may be the culprit.
我注意到 PHP 版本 5.14.12 的这种行为,其他版本也可能如此。
当使用 file_get_contents 将 JSON 字符串加载到 json_decode 函数中时,我必须去掉 BOM 字符,即 UTF-8 EF BB BF 才能正常工作。
比较两个字符串的长度——硬编码与传入的变量——如果它们不一样,这些字符可能是罪魁祸首。
回答by Carlton
Useful post from Sebastian about the json output format
Sebastian 关于 json 输出格式的有用帖子
https://github.com/sebastianbergmann/phpunit/issues/142
https://github.com/sebastianbergmann/phpunit/issues/142
Using Keith's suggestion will allow the data to be parsed correctly
使用 Keith 的建议将允许正确解析数据
回答by shadow_of__soul
try to set the error reporting in ALL, the json_decode() should give you a notice in the offset where the conversion fails.
尝试在 ALL 中设置错误报告,json_decode() 应该在转换失败的偏移量中给你一个通知。

