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

时间:2020-12-09 20:29:41

I have this JSON object stored on a plain text file:

我将这个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"
    }
}

When I try to decode it with json_decode(), it returns NULL. Why? The file is readable (I tried echoing file_get_contents() and it worked ok).

当我尝试用json_decode()解码它时,它返回NULL。为什么?该文件是可读的(我尝试了echo file_get_contents(),它运行良好)。

I've tested JSON against http://jsonlint.com/ and it's perfectly valid.

我已经在http://jsonlint.com/上测试了JSON,它非常有效。

What's wrong here?

有什么问题吗?

Solution

Looking for answers on Google, I got back to SO: json_decode returns NULL after webservice call. My JSON file had the UTF BOM sequence (some binary chars that shouldn't be there), thus, breaking the JSON structure. Went to Hex Editor, erased the bytes. Everything's back to normal. Why has this happened? Because I edited the file using Microsoft Windows' Notepad. Terrible idea!

寻找谷歌的答案,我回到了SO: json_decode在webservice调用后返回NULL。我的JSON文件具有UTF BOM序列(一些不应该存在的二进制字符),从而破坏了JSON结构。转到十六进制编辑器,删除了字节。一切都恢复正常。这为什么会发生?因为我是用微软Windows记事本编辑的。可怕的主意!

16 个解决方案

#1


47  

It could be the encoding of the special characters. You could ask json_last_error() to get definite information.

它可以是特殊字符的编码。您可以询问json_last_error()以获得明确的信息。

Update: The issue is solved, look at the "Solution" paragraph in the question.

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

#2


42  

This worked for me

这为我工作

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

#3


19  

If you check the the request in chrome you will see that the JSON is text, so there has been blank code added to the JSON.

如果您在chrome中检查了请求,您将看到JSON是文本,因此JSON中添加了空白代码。

You can clear it by using

你可以用它来清除它。

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

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

Then you can use:

然后您可以使用:

json_decode($k)

json_decode(k)美元

print_r will then show the array.

然后print_r将显示数组。

#4


11  

I had the same problem and I solved it simply by replacing the quote character before decode.

我遇到了同样的问题,我只是简单地用“解码”替换了引号。

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

My JSON value was generated by JSON.stringify function.

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

#5


8  

Maybe some hidden characters are messing with your json, try this:

也许一些隐藏的字符正在干扰你的json,试试这个:

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

#6


7  

You could try with it.

你可以试试。

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

#7


6  

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

did it for me. And yes, testing on Chrome. Thx to user2254008

是为了我才这样做的。是的,在Chrome上测试。谢谢,user2254008

#8


4  

Just thought I'd add this, as I ran into this issue today. If there is any string padding surrounding your JSON string, json_decode will return NULL.

我想补充一下,今天我遇到了这个问题。如果JSON字符串周围有任何字符串填充,json_decode将返回NULL。

If you're pulling the JSON from a source other than a PHP variable, it would be wise to "trim" it first:

如果您是从一个PHP变量以外的源中提取JSON,那么最好先“修剪”它:

$jsonData = trim($jsonData);

#9


1  

As stated by Jürgen Math using the preg_replace method listed by user2254008 fixed it for me as well.

正如Jurgen Math所述,使用user2254008所列出的preg_replace方法也为我修复了它。

This is not limited to Chrome, it appears to be a character set conversion issue (at least in my case, Unicode -> UTF8) This fixed all the issues i was having.

这并不局限于Chrome,它似乎是一个字符集转换问题(至少在我的例子中,Unicode -> UTF8)解决了我所遇到的所有问题。

As a future node, the JSON Object i was decoding came from Python's json.dumps function. This in turn caused some other unsanitary data to make it across though it was easily dealt with.

作为未来的节点,我正在解码的JSON对象来自Python的JSON。转储函数。这反过来又导致了一些其他不卫生的数据,尽管它很容易处理。

#10


1  

If you are getting json from database, put

如果从数据库获取json,请输入。

mysqli_set_charset($con, "utf8");

after defining connection link $con

在定义连接链接$con之后。

#11


1  

Just save some one time. I spent 3 hours to find out that it was just html encoding problem. Try this

省省吧。我花了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);

#12


1  

this help you to understand what is the type of error

这将帮助您理解错误的类型。

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

#13


1  

Here you can find little JSON wrapper with corrective actions that addresses BOM and non-ASCI issue: https://*.com/a/43694325/2254935

在这里,您可以找到针对BOM和非asci问题的纠正操作的小JSON包装:https://*.com/a/43694325/2254935。

#14


0  

I've solved this issue by printing the JSON, and then checking the page source (CTRL/CMD + U):

我已经通过打印JSON解决了这个问题,然后检查页面源代码(CTRL/CMD + U):

print_r(file_get_contents($url));

Turned out there was a trailing <pre> tag.

结果显示有一个尾随

标记。

#15


0  

you should ensure these points

你应该确保这些要点。

1. your json string dont have any unknowns characters

1。json字符串没有任何未知字符。

2. json string can view from online json viewer (you can search on google as online viewer or parser for json) it should view without any error

2。json字符串可以从在线json查看器(您可以在谷歌上搜索作为json的在线查看器或解析器)查看,它应该没有任何错误。

3. your string dont have html entities it should be plain text/string

3所示。您的字符串没有html实体,它应该是纯文本/字符串。

for explanation of point 3

关于第3点的解释。

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

to (remove htmlentities() function )

to(删除htmlentities()函数)

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

#16


-5  

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

#1


47  

It could be the encoding of the special characters. You could ask json_last_error() to get definite information.

它可以是特殊字符的编码。您可以询问json_last_error()以获得明确的信息。

Update: The issue is solved, look at the "Solution" paragraph in the question.

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

#2


42  

This worked for me

这为我工作

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

#3


19  

If you check the the request in chrome you will see that the JSON is text, so there has been blank code added to the JSON.

如果您在chrome中检查了请求,您将看到JSON是文本,因此JSON中添加了空白代码。

You can clear it by using

你可以用它来清除它。

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

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

Then you can use:

然后您可以使用:

json_decode($k)

json_decode(k)美元

print_r will then show the array.

然后print_r将显示数组。

#4


11  

I had the same problem and I solved it simply by replacing the quote character before decode.

我遇到了同样的问题,我只是简单地用“解码”替换了引号。

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

My JSON value was generated by JSON.stringify function.

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

#5


8  

Maybe some hidden characters are messing with your json, try this:

也许一些隐藏的字符正在干扰你的json,试试这个:

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

#6


7  

You could try with it.

你可以试试。

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

#7


6  

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

did it for me. And yes, testing on Chrome. Thx to user2254008

是为了我才这样做的。是的,在Chrome上测试。谢谢,user2254008

#8


4  

Just thought I'd add this, as I ran into this issue today. If there is any string padding surrounding your JSON string, json_decode will return NULL.

我想补充一下,今天我遇到了这个问题。如果JSON字符串周围有任何字符串填充,json_decode将返回NULL。

If you're pulling the JSON from a source other than a PHP variable, it would be wise to "trim" it first:

如果您是从一个PHP变量以外的源中提取JSON,那么最好先“修剪”它:

$jsonData = trim($jsonData);

#9


1  

As stated by Jürgen Math using the preg_replace method listed by user2254008 fixed it for me as well.

正如Jurgen Math所述,使用user2254008所列出的preg_replace方法也为我修复了它。

This is not limited to Chrome, it appears to be a character set conversion issue (at least in my case, Unicode -> UTF8) This fixed all the issues i was having.

这并不局限于Chrome,它似乎是一个字符集转换问题(至少在我的例子中,Unicode -> UTF8)解决了我所遇到的所有问题。

As a future node, the JSON Object i was decoding came from Python's json.dumps function. This in turn caused some other unsanitary data to make it across though it was easily dealt with.

作为未来的节点,我正在解码的JSON对象来自Python的JSON。转储函数。这反过来又导致了一些其他不卫生的数据,尽管它很容易处理。

#10


1  

If you are getting json from database, put

如果从数据库获取json,请输入。

mysqli_set_charset($con, "utf8");

after defining connection link $con

在定义连接链接$con之后。

#11


1  

Just save some one time. I spent 3 hours to find out that it was just html encoding problem. Try this

省省吧。我花了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);

#12


1  

this help you to understand what is the type of error

这将帮助您理解错误的类型。

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

#13


1  

Here you can find little JSON wrapper with corrective actions that addresses BOM and non-ASCI issue: https://*.com/a/43694325/2254935

在这里,您可以找到针对BOM和非asci问题的纠正操作的小JSON包装:https://*.com/a/43694325/2254935。

#14


0  

I've solved this issue by printing the JSON, and then checking the page source (CTRL/CMD + U):

我已经通过打印JSON解决了这个问题,然后检查页面源代码(CTRL/CMD + U):

print_r(file_get_contents($url));

Turned out there was a trailing <pre> tag.

结果显示有一个尾随

标记。

#15


0  

you should ensure these points

你应该确保这些要点。

1. your json string dont have any unknowns characters

1。json字符串没有任何未知字符。

2. json string can view from online json viewer (you can search on google as online viewer or parser for json) it should view without any error

2。json字符串可以从在线json查看器(您可以在谷歌上搜索作为json的在线查看器或解析器)查看,它应该没有任何错误。

3. your string dont have html entities it should be plain text/string

3所示。您的字符串没有html实体,它应该是纯文本/字符串。

for explanation of point 3

关于第3点的解释。

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

to (remove htmlentities() function )

to(删除htmlentities()函数)

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

#16


-5  

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