PHP的json_decode()返回NULL与有效的JSON?

我有这个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() ,它工作正常)。

我已经testing了JSON对http://jsonlint.com/ ,这是完全有效的。

这里有什么问题?

在Google上寻找答案,我回到了所以: json_decode在webservice调用后返回NULL 。 我的JSON文件具有UTF BOM序列(一些二进制字符不应该在那里),因此打破了JSON结构。 去了hex编辑器,擦除了字节。 一切都恢复正常。 为什么发生这种事? 因为我使用Microsoft Windows'记事本编辑了文件。 可怕的主意!

这可能是特殊字符的编码。 你可以问json_last_error()来获得确定的信息。

更新:问题解决了,看问题中的“解决scheme”段落。

这对我有效

 json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string), true ); 

如果你在chrome中检查请求,你会看到JSON是文本,所以有一些空白的代码添加到JSON中。

您可以使用清除它

$k=preg_replace('/\s+/', '',$k);

那么你可以使用:

json_decode($k)

print_r将显示数组。

我有同样的问题,我解决它简单地通过在解码之前replace引号字符。

 $json = str_replace('"', '"', $json); $object = json_decode($json); 

我的JSON值是由JSON.stringify函数生成的。

 $k=preg_replace('/\s+/', '',$k); 

为我做了。 是的,在Chrome上进行testing。 Thx到user2254008

你可以尝试一下。

 json_decode(stripslashes($_POST['data'])) 

也许一些隐藏的字符与你的json搞混了,试试这个:

 $json = utf8_encode($yourString); $data = json_decode($json); 

只是觉得我会加上这个,就像今天遇到这个问题一样。 如果JSONstring周围有任何string填充,json_decode将返回NULL。

如果您从PHPvariables以外的来源提取JSON,那么先“修剪”它将是明智之举:

 $jsonData = trim($jsonData); 

正如JürgenMath所述,使用user2254008列出的preg_replace方法也为我解决了这个问题。

这不仅限于Chrome,它似乎是一个字符集转换问题(至less在我的情况下,Unicode – > UTF8)这解决了我所有的问题。

作为未来的节点,我解码的JSON对象来自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,然后检查页面源代码(CTRL / CMD + U)来解决这个问题:

 print_r(file_get_contents($url)); 

原来有一个尾随的<pre>标签。

这有助于你了解什么是错误的types

 <?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; } ?> 

你应该确保这些点

1.你的jsonstring没有任何未知的字符

2. jsonstring可以从在线json查看器查看(您可以在谷歌search作为在线查看器或jsonparsing器)它应该查看没有任何错误

3.你的string没有html实体,它应该是纯文本/string

为了解释第3点

 $html_product_sizes_json=htmlentities($html); $ProductSizesArr = json_decode($html_product_sizes_json,true); 

(去掉htmlentities()函数)

 $html_product_sizes_json=$html; $ProductSizesArr = json_decode($html_product_sizes_json,true); 

在这里你可以find一些解决BOM和非ASCI问题的纠正措施的小JSON包装: https : //stackoverflow.com/a/43694325/2254935

 <?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>"; ?>