json_decode返回JSON_ERROR_SYNTAX但在线格式化程序说JSON没问题

Jea*_*ane 33 php json

我有一个非常奇怪的问题.

我有一个JSON Web服务.

当我在这个网站上查看http://www.freeformatter.com/json-formatter.html#ad-output

一切都好.

但是当我用这段代码加载我的JSON时:

  $data = file_get_contents('http://www.mywebservice');

if(!empty($data))
{

    $obj = json_decode($data);

 switch (json_last_error()) {
    case JSON_ERROR_NONE:
        echo ' - JSON_ERROR_NONE';
    break;
    case JSON_ERROR_DEPTH:
        echo ' - JSON_ERROR_DEPTH';
    break;
    case JSON_ERROR_STATE_MISMATCH:
        echo ' - JSON_ERROR_STATE_MISMATCH';
    break;
    case JSON_ERROR_CTRL_CHAR:
        echo ' -  JSON_ERROR_CTRL_CHAR';
    break;
    case JSON_ERROR_SYNTAX:
        echo "\r\n\r\n - SYNTAX ERROR \r\n\r\n";
    break;
    case JSON_ERROR_UTF8:
        echo ' - JSON_ERROR_UTF8';
    break;
    default:
        echo ' - Unknown erro';
    break;
}
Run Code Online (Sandbox Code Playgroud)

我收到错误:SYNTAX ERROR

什么都没有完全帮助.

这是一场噩梦.

我看到用PHP 5.5我可以使用这个函数:http://php.net/manual/en/function.json-last-error-msg.php

(但我还没有成功安装PHP 5.5,我不确定这个功能会给我更多细节)

Kri*_*lah 73

我遇到了同样的问题,实际上有一些看不见的隐藏字符,你需要删除它.这是一个适用于许多情况的全局代码:

<?php
$checkLogin = file_get_contents("http://yourwebsite.com/JsonData");

// This will remove unwanted characters.
// Check http://www.php.net/chr for details
for ($i = 0; $i <= 31; ++$i) { 
    $checkLogin = str_replace(chr($i), "", $checkLogin); 
}
$checkLogin = str_replace(chr(127), "", $checkLogin);

// This is the most common part
// Some file begins with 'efbbbf' to mark the beginning of the file. (binary level)
// here we detect it and we remove it, basically it's the first 3 characters 
if (0 === strpos(bin2hex($checkLogin), 'efbbbf')) {
   $checkLogin = substr($checkLogin, 3);
}

$checkLogin = json_decode( $checkLogin );
print_r($checkLogin);
?>
Run Code Online (Sandbox Code Playgroud)

  • 亲爱的先生,您不知道这对我有多大帮助.我到处寻找解决方案,我几乎放弃了.先生,你是天赐之物. (2认同)

Gre*_*ett 48

删除BOM(字节顺序标记)通常是您需要的解决方案:

function removeBOM($data) {
    if (0 === strpos(bin2hex($data), 'efbbbf')) {
       return substr($data, 3);
    }
    return $data;
}
Run Code Online (Sandbox Code Playgroud)

您不应该有BOM,但如果它在那里,它是隐形的,所以你不会看到它!

在HTML中查看BOM上的W3C

如果你有很多要修复的文件,请使用BOM清理器.

  • 我已将Notepad ++的顶部菜单中的Notepad ++将编码从UTF-8更改为UTF-8不带BOM的格式。 (2认同)

小智 28

我解决了这个问题,增加的stripslashes字符串,json_decode之前.

$data = stripslashes($data); 
$obj = json_decode($data);
Run Code Online (Sandbox Code Playgroud)

  • 不应该是$ data = stripslashes($ data); (3认同)

Krz*_*oda 7

为了把所有的东西放在一起,我已经准备了JSON包装器,解码自动纠正措施.最新版本可以在我的GitHub Gist中找到.

abstract class Json
{
    public static function getLastError($asString = FALSE)
    {
        $lastError = \json_last_error();

        if (!$asString) return $lastError;

        // Define the errors.
        $constants = \get_defined_constants(TRUE);
        $errorStrings = array();

        foreach ($constants["json"] as $name => $value)
            if (!strncmp($name, "JSON_ERROR_", 11))
                $errorStrings[$value] = $name;

        return isset($errorStrings[$lastError]) ? $errorStrings[$lastError] : FALSE;
    }

    public static function getLastErrorMessage()
    {
        return \json_last_error_msg();
    }

    public static function clean($jsonString)
    {
        if (!is_string($jsonString) || !$jsonString) return '';

        // Remove unsupported characters
        // Check http://www.php.net/chr for details
        for ($i = 0; $i <= 31; ++$i)
            $jsonString = str_replace(chr($i), "", $jsonString);

        $jsonString = str_replace(chr(127), "", $jsonString);

        // Remove the BOM (Byte Order Mark)
        // It's the most common that some file begins with 'efbbbf' to mark the beginning of the file. (binary level)
        // Here we detect it and we remove it, basically it's the first 3 characters.
        if (0 === strpos(bin2hex($jsonString), 'efbbbf')) $jsonString = substr($jsonString, 3);

        return $jsonString;
    }

    public static function encode($value, $options = 0, $depth = 512)
    {
        return \json_encode($value, $options, $depth);
    }

    public static function decode($jsonString, $asArray = TRUE, $depth = 512, $options = JSON_BIGINT_AS_STRING)
    {
        if (!is_string($jsonString) || !$jsonString) return NULL;

        $result = \json_decode($jsonString, $asArray, $depth, $options);

        if ($result === NULL)
            switch (self::getLastError())
            {
                case JSON_ERROR_SYNTAX :
                    // Try to clean json string if syntax error occured
                    $jsonString = self::clean($jsonString);
                    $result = \json_decode($jsonString, $asArray, $depth, $options);
                    break;

                default:
                    // Unsupported error
            }

        return $result;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

$json_data = file_get_contents("test.json");
$array = Json::decode($json_data, TRUE);
var_dump($array);
echo "Last error (" , Json::getLastError() , "): ", Json::getLastError(TRUE), PHP_EOL;
Run Code Online (Sandbox Code Playgroud)


小智 5

就我而言:

json_decode(html_entity_decode($json_string));


med*_*eda 1

您还没有显示您的 JSON,但这听起来可能是参数中的无效 UTF-8 序列,大多数在线验证器不会捕获它。确保您的数据是 UTF-8,并检查是否有外来字符。您不需要 PHP5 来查看错误,使用error_log()来记录问题。