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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2410342/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:21:31  来源:igfitidea点击:

PHP json_decode() returns NULL with valid JSON?

phpjsonnull

提问by Joel A. Villarreal Bertoldi

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。为什么?该文件是可读的(我尝试回显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!

在 Google 上寻找答案,我回到了 SO:json_decode 返回 NULL after webservice call。我的 JSON 文件具有 UTF BOM 序列(一些不应该存在的二进制字符),因此破坏了 JSON 结构。转到十六进制编辑器,擦除字节。一切恢复正常。为什么会发生这种情况?因为我使用 Microsoft Windows 的记事本编辑了该文件。可怕的想法!

采纳答案by Pekka

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.

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

回答by Dunith Dhanushka

This worked for me

这对我有用

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

回答by Gabriel Castillo Prada

You could try with it.

你可以试试看。

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

回答by user2254008

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_rwill then show the array.

print_r然后将显示数组。

回答by Yapp Ka Howe

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 函数生成的。

回答by Albert Abdonor

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

也许一些隐藏的字符弄乱了你的 json,试试这个:

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

回答by Jürgen Math

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

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

为我做的。是的,在 Chrome 上测试。感谢 user2254008

回答by Phil LaNasa

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);

回答by Enrico Tempesti

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

回答by Samuel Kwame Antwi

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);