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

时间:2010-03-09 15:51:14

标签: php 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 returns NULL after webservice call。我的JSON文件具有UTF BOM序列(一些不应该存在的二进制字符),因此打破了JSON结构。去十六进制编辑器,删除了字节。一切都恢复正常。 为什么会这样? 因为我使用Microsoft Windows的记事本编辑了文件。糟糕的主意!

29 个答案:

答案 0 :(得分:61)

这对我有用

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

答案 1 :(得分:58)

它可能是特殊字符的编码。您可以要求json_last_error()获取明确的信息。

  

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

答案 2 :(得分:23)

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

您可以使用

清除它

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

然后你可以使用:

json_decode($k)

然后

print_r将显示该数组。

答案 3 :(得分:19)

你可以尝试一下。

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

答案 4 :(得分:12)

我遇到了同样的问题,我只是通过在解码前替换引号来解决它。

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

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

答案 5 :(得分:9)

也许有些隐藏的角色正在弄乱你的json,试试这个:

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

答案 6 :(得分:6)

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

为我做了。是的,在Chrome上测试。请转至user2254008

答案 7 :(得分:4)

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

如果你从PHP变量以外的源中提取JSON,那么首先“修剪”它是明智的:

$jsonData = trim($jsonData);

答案 8 :(得分:2)

这有助于您了解错误的类型

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

答案 9 :(得分:1)

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

mysqli_set_charset($con, "utf8");

定义连接链接$ con

之后

答案 10 :(得分:1)

只需保存一次。我花了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);

答案 11 :(得分:1)

如JürgenMath所述,使用user2254008列出的preg_replace方法也为我修复了它。

这不仅限于Chrome,它似乎是一个字符集转换问题(至少在我的情况下,Unicode - &gt; UTF8)这解决了我遇到的所有问题。

作为未来的节点,我正在解码的JSON Object来自Python的json.dumps函数。这反过来导致一些其他不卫生的数据通过它很容易处理。

答案 12 :(得分:1)

所以html_entity_decode()为我工作了。请尝试这个。

$input = file_get_contents("php://input");
$input = html_entity_decode($input);
$event_json = json_decode($input,true);

答案 13 :(得分:1)

在应用 PHP 相关解决方案之前,请验证您的 JSON 格式。也许这就是问题所在。试试这个在线 JSON 格式验证器。 https://jsonformatter.org/

答案 14 :(得分:1)

在这里,您可以找到一些小JSON包装器,其中包含解决BOM和非ASCI问题的纠正措施:https://stackoverflow.com/a/43694325/2254935

答案 15 :(得分:1)

就我而言,我遇到了同样的问题,但它是由 json 字符串中的斜杠引起的,因此使用

json_decode(stripslashes($YourJsonString))

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

如果上述方法不起作用,请先替换 html quote 中的引号,如果您从 javascript 向 php 发送数据,则可能会发生这种情况

    $YourJsonString = stripslashes($YourJsonString);
    $YourJsonString = str_replace('&quot;', '"', $YourJsonString);
    $YourJsonString = str_replace('["', '[', $YourJsonString);
    $YourJsonString = str_replace('"]', ']', $YourJsonString);
    $YourJsonString = str_replace('"{', '{', $YourJsonString);
    $YourJsonString = str_replace('}"', '}', $YourJsonString);
    $YourJsonObject = json_decode($YourJsonString);

会解决的,

答案 16 :(得分:1)

我遇到了完全相同的问题 但是用这个代码修复了

$zip = file_get_contents($file);
$zip = json_decode(stripslashes($zip), true);

答案 17 :(得分:0)

我建议创建一个.json文件(例如:config.json)。 然后粘贴所有json对象并 format 。因此,您将能够删除所有破坏json对象的东西,并获得干净的复制粘贴json对象。

答案 18 :(得分:0)

  • 我也面临着同样的问题...
  • 我修复了以下步骤... 1)在浏览器中打印该变量2)通过freeformatter验证该变量数据3)复制/引用该数据以进行进一步处理
  • 那之后,我没有任何问题。

答案 19 :(得分:0)

对我来说,php 函数 stripslashes() 在从 javascript 接收 json 时起作用。当从 python 接收 json 时,json_decode 调用的第二个可选参数会起作用,因为数组是关联的。对我来说就像一个魅力。

$json = stripslashes($json); //add this line if json from javascript
$edit = json_decode($json, true); //adding parameter true if json from python

答案 20 :(得分:0)

我遇到了同样的问题,但没有一个答案对我有帮助。 我的 JSON 对象中的变量之一具有值 main.sh: ASCII text 。我删除了这个 Andaman & Nicobar,我的代码运行良好。

答案 21 :(得分:0)

在这里我解决了我的https://stackoverflow.com/questions/17219916/64923728 .. JSON文件必须在UTF-8中编码我的文件在UTF-8中且带有BOM表,这给&65279; 导致json_decode()返回null的json字符串输出

答案 22 :(得分:0)

我花了一个小时才弄清楚,但是在PHP中尾随逗号(在JavaScript中有效)失败。
这就是为我解决的问题:

str_replace([PHP_EOL, ",}"], ["", "}"], $JSON);

答案 23 :(得分:0)

要记住的最重要的事情是,从有效的JSON数据中获得NULL结果时,请使用以下命令:

json_last_error_msg();

即。

var_dump(json_last_error_msg());
string(53) "Control character error, possibly incorrectly encoded"

然后您可以通过以下方式解决此问题:

$new_json = preg_replace('/[[:cntrl:]]/', '', $json);

答案 24 :(得分:0)

对我来说,我必须关闭 error_reporting ,以使json_decode()正常工作。听起来很奇怪,但就我而言是真实的。因为我尝试解码的JSON字符串之间印有一些通知。

答案 25 :(得分:0)

就我而言,这是因为JSON字符串中的单引号。

JSON格式仅接受键和字符串值的双引号。

示例:

$jsonString = '{\'hello\': \'PHP\'}'; // valid value should be '{"hello": "PHP"}'
$json = json_decode($jsonString);
print $json; // null

由于Javascript语法,我对此感到困惑。当然,在Javascript中,我们可以这样:

let json = {
    hello: 'PHP' // no quote for key, single quote for string value
}

// OR:
json = {
    'hello': 'PHP' // single quote for key and value
}

但是稍后将这些对象转换为JSON字符串时:

JSON.stringify(json); // "{"hello":"PHP"}"

答案 26 :(得分:0)

你应该确保这些要点

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

2. json字符串可以从在线json查看器中查看(您可以在google上搜索为json的在线查看器或解析器)它应该可以查看而不会出现任何错误

3。你的字符串没有html实体它应该是纯文本/字符串

解释第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);

答案 27 :(得分:0)

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

print_r(file_get_contents($url));

原来有一个跟踪<pre>标记。

答案 28 :(得分:-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>";
?>
相关问题