PHP json_decode()返回带有效JSON的NULL?
我将此JSON对象存储在纯文本文件中:
{
"MySQL": {
"Server": "(server)",
"Username": "(user)",
"Password": "(pwd)",
"DatabaseName": "(dbname)"
},
"Ftp": {
"Server": "(server)",
"Username": "(user)",
"Password": "(pwd)",
"RootFolder": "(rf)"
},
"BasePath": "../../bin/",
"NotesAppPath": "notas",
"SearchAppPath": "buscar",
"BaseUrl": "http:\/\/montemaiztusitio.com.ar",
"InitialExtensions": [
"nem.mysqlhandler",
"nem.string",
"nem.colour",
"nem.filesystem",
"nem.rss",
"nem.date",
"nem.template",
"nem.media",
"nem.measuring",
"nem.weather",
"nem.currency"
],
"MediaPath": "media",
"MediaGalleriesTable": "journal_media_galleries",
"MediaTable": "journal_media",
"Journal": {
"AllowedAdFileFormats": [
"flv:1",
"jpg:2",
"gif:3",
"png:4",
"swf:5"
],
"AdColumnId": "3",
"RSSLinkFormat": "%DOMAIN%\/notas\/%YEAR%-%MONTH%-%DAY%\/%TITLE%/",
"FrontendLayout": "Flat",
"AdPath": "ad",
"SiteTitle": "Monte Maíz: Tu Sitio",
"GlobalSiteDescription": "Periódico local de Monte Maíz.",
"MoreInfoAt": "Más información aquí, en el Periódico local de Monte Maíz.",
"TemplatePath": "templates",
"WeatherSource": "accuweather:SAM|AR|AR005|MONTE MAIZ",
"WeatherMeasureType": "1",
"CurrencySource": "cotizacion-monedas:Dolar|Euro|Real",
"TimesSingular": "vez",
"TimesPlural": "veces"
}
}
当我尝试用json_decode()
解码它时,它返回NULL。 为什么?该文件是可读的(我尝试回复file_get_contents()
,它工作正常)。
我已经针对[http://jsonlint.com/]测试了JSON,它完全有效。
这有什么不对?
解
在Google上寻找答案,我回到了SO:json_decode在webservice调用后返回NULL。 我的JSON文件具有UTF BOM序列(一些不应该存在的二进制字符),因此打破了JSON结构。 去十六进制编辑器,删除了字节。 一切都恢复正常。为什么会这样? 因为我使用Microsoft Windows的记事本编辑了该文件。 糟糕的主意!
它可能是特殊字符的编码。 您可以要求json_last_error()获取明确的信息。
更新:问题已解决,请查看问题中的“解决方案”段落。
这对我有用
json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string), true );
如果您在chrome中检查请求,您将看到JSON是文本,因此JSON中添加了空白代码。
您可以使用清除它
print_r
然后你可以使用:
print_r
print_r
然后将显示该数组。
你可以尝试一下。
json_decode(stripslashes($_POST['data']))
我有同样的问题,我只是通过在解码前替换引号字符解决它。
$json = str_replace('"', '"', $json);
$object = json_decode($json);
我的JSON值是由JSON.stringify函数生成的。
也许一些隐藏的角色正在弄乱你的json,试试这个:
$json = utf8_encode($yourString);
$data = json_decode($json);
$k=preg_replace('/\s+/', '',$k);
为我做了 是的,在Chrome上测试。 请转至user2254008
刚想到我会添加这个,因为我今天遇到了这个问题。 如果JSON字符串周围有任何字符串填充,json_decode将返回NULL。
如果您从PHP变量以外的源中提取JSON,那么首先“修剪”它是明智的:
$jsonData = trim($jsonData);
这有助于您了解错误的类型
<?php
// A valid json string
$json[] = '{"Organization": "PHP Documentation Team"}';
// An invalid json string which will cause an syntax
// error, in this case we used ' instead of " for quotation
$json[] = "{'Organization': 'PHP Documentation Team'}";
foreach ($json as $string) {
echo 'Decoding: ' . $string;
json_decode($string);
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}
echo PHP_EOL;
}
?>
正如JürgenMath所说,使用user2254008列出的preg_replace方法也为我修复了它。
这不仅限于Chrome,它似乎是字符集转换问题(至少在我的情况下,Unicode - &gt; UTF8)这解决了我遇到的所有问题。
作为未来的节点,我正在解码的JSON Object来自Python的json.dumps函数。 这反过来导致一些其他不卫生的数据,虽然它很容易处理。
如果您从数据库获取json,请将其放入
mysqli_set_charset($con, "utf8");
在定义连接链接$ con之后
只需保存一次。 我花了3个小时才发现它只是html编码问题。 试试这个
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);
在这里,您可以找到小JSON包装器,其中包含解决BOM和非ASCI问题的纠正措施:[https://stackoverflow.com/a/43694325/2254935]
我通过打印JSON,然后检查页面源(CTRL / CMD + U)解决了这个问题:
print_r(file_get_contents($url));
原来有一个尾随<pre>
标签。
你应该确保这些要点
1.你的json字符串没有任何未知字符
2. json字符串可以从在线json查看器查看(你可以在google上搜索为json的在线查看器或解析器)它应该查看没有任何错误
3.你的字符串没有html实体,它应该是纯文本/字符串
解释第3点
$html_product_sizes_json=htmlentities($html);
$ProductSizesArr = json_decode($html_product_sizes_json,true);
to(删除htmlentities()函数)
$html_product_sizes_json=$html;
$ProductSizesArr = json_decode($html_product_sizes_json,true);
<?php
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$data = json_decode($json);
echo "<pre>";
print_r($data);
echo "</pre>";
?>