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

我遇到了一个非常奇怪的问题。</ p>

我有一个JSON网络服务。 </ p>

当我在本网站上查看时, http ://www.freeformatter.com/json-formatter.html#ad-output </ p>

一切正常。</ p>

但是当 我用这段代码加载我的JSON:</ p>

  $ 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:\ n 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“

  • SYNTAX ERROR

”;
中断;
大小写JSON_ERROR_UT F8:
echo' - JSON_ERROR_UTF8';
break;
默认值:
echo' - 未知错误';
break;
}
</ code> </ pre>

我收到了错误:SYNTAX ERROR </ p>

什么都没有全部帮助。</ p>

这是一场噩梦。 </ p>

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

(但我做了) 还没有成功安装PHP 5.5,我不确定这个功能会给我更多细节)</ p>
</ div>

展开原文

原文

I got a very strange problem.

I have a JSON webservice.

When i check it with this website http://www.freeformatter.com/json-formatter.html#ad-output

Everything is OK.

But when i load my JSON with this code :

  $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 "

 - SYNTAX ERROR 

";
    break;
    case JSON_ERROR_UTF8:
        echo ' - JSON_ERROR_UTF8';
    break;
    default:
        echo ' - Unknown erro';
    break;
}

I got the error : SYNTAX ERROR

WHICH IS NOT HELP FULL AT ALL.

It is a nightmare.

I see that with PHP 5.5 i could use this function : http://php.net/manual/en/function.json-last-error-msg.php

(but i did not succeed to install PHP 5.5 yet, and i m not sure this function will give me more detail)

drjgk44268
drjgk44268 也许你应该让你的错误消息更详细?例如,包含带有错误消息的JSON?
7 年多之前 回复
douya7309
douya7309 请JSON。我们需要你的JSON。
7 年多之前 回复
dpruwm6206
dpruwm6206 请显示JSON。
7 年多之前 回复

11个回答

I faced the same issue, actually there are some hidden characters unseen and you need to remove it. Here's a global code that works for many cases:

<?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);
?>
douou2026
douou2026 我从支付网关API响应中收到此错误。 这是语法错误的修复。 特别是过滤掉'efbbbf'。
大约一年之前 回复
douxian3828
douxian3828 微软的freakin合作伙伴中心api返回BOM? 为什么?!!!
接近 3 年之前 回复
douchuoxuan3177
douchuoxuan3177 这有助于我的情况... for($ i = 0; $ i <= 31; ++ $ i){$ checkLogin = str_replace(chr($ i),“”,$ checkLogin); } 但为什么??
接近 3 年之前 回复
dreamwind1985
dreamwind1985 BOM的+1,没想到。 @GeorgeOnofrei,单一责任原则将规定,如果字符串包含无效字符,或者技术上不属于JSON文档本身的BOM,则执行清理不是此功能的目的!
3 年多之前 回复
dongshi3361
dongshi3361 仍然想知道为什么这不是7.0.x版本的核心PHP的一部分。 (脸掌)
大约 4 年之前 回复
dsolwotv00116
dsolwotv00116 亲爱的先生,您不知道这对我有多大帮助。 我到处寻找解决方案,我几乎放弃了。 先生,你是天赐之物。
接近 6 年之前 回复

To put all things together here and there, I've prepared JSON wrapper with decoding auto corrective actions. Most recent version can be found in my 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;
    }
}

Example usage:

$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;
duanji1056
duanji1056 像魅力一样为我工作! 非常感谢!!
大约 2 年之前 回复
douhao6271
douhao6271 我一直在与一个包含JSON的奇怪编码文件进行战斗,这个类终于让我有了一个可用的PHP数组 - 谢谢!
接近 3 年之前 回复



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

展开原文

原文

You haven't show your JSON but this sound like it could be an Invalid UTF-8 sequence in argument, most online validator wont catch it. make sure your data is UTF-8 and also check if you have foreign characters. You don't need PHP5 to see your error, use error_log() to log the problems.

After trying all the solution without the result this is the one worked for me.

Hope it will help someone

$data = str_replace('&quot;', '"', $data);



我遇到同样的问题,收到 JSON_ERROR_CTRL_CHAR </ strong>和 JSON_ERROR_SYNTAX </ strong>。


这是我的修复。</ p>

  $ content = json_decode(json_encode($ content),true); 
</ code> </ pre>
</ div>

展开原文

原文

I have the same problem, receiving JSON_ERROR_CTRL_CHAR and JSON_ERROR_SYNTAX.
This is my fix.

$content = json_decode(json_encode($content), true);



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

  function removeBOM($ data){
if(0 === strpos(bin2hex($ data),'efbbbf')){
return substr($ data,3);

}
返回$ data;
}
</ code> </ pre>

您不应该有BOM,但是如果它在那里,它是不可见的,所以你不会 看到它!! </ p>

参见使用HTML格式的BOM上的W3C </ p>

使用 BOM Cleaner 如果你有很多要修复的文件。</ p>
</ div>

展开原文

原文

Removing the BOM (Byte Order Mark) is often-times the solution you need:

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

You shouldn't have a BOM, but if it's there, it is invisible so you won't see it!!

see W3C on BOM's in HTML

use BOM Cleaner if you have lot's of files to fix.

duandgfh0506
duandgfh0506 这对我来说很有用! 谢谢
一年多之前 回复
douyue6520
douyue6520 在找到这个答案之前,几乎花了将近1个小时尝试了一百万件事......谢谢堆!
2 年多之前 回复
dongxie3701
dongxie3701 我已经从Notepad ++>格式> UTF-8的顶部菜单中将NoteF ++从UTF-8转换为UTF-8而不使用BOM而没有BOM
接近 4 年之前 回复



我解决了这个问题,在json_decode之前将 stripslashes </ strong>添加到字符串。</ p>

  $ data = stripslashes($ data);

$ obj = json_decode($ data);
</ code> </ pre>
</ div>

展开原文

原文

I solved this issue adding stripslashes to the string, before json_decode.

$data = stripslashes($data); 
$obj = json_decode($data);

dongzong2017
dongzong2017 不应该是$ data = stripslashes($ data);
接近 5 年之前 回复
douzheren3349
douzheren3349 请格式化您的代码。 谢谢。
5 年多之前 回复



我遇到了同样的问题。 我采取了以下步骤:</ p>


  1. 更改了JSON文本编码</ p>

      $ json = utf8_encode($  json); 
    </ code> </ pre> </ li>
  2. 然后我在解码之前查看了纯文本。 我找到了疯狂的符号,比如</ p>

    ï</ code> </ p> </ li>

  3. 然后我就把它剥掉了</ p>

      $ json = str_replace(array('ï',''),'',$ json); 
    </ code> </ pre>
  4. 和 我成功解码了我的JSON </ p> </ li>
    </ ol>
    </ div>

展开原文

原文

I had the same issues. I took the following steps:

  1. changed the JSON text encoding

    $json = utf8_encode($json);
    
  2. I then viewed the plain text before decoding. I found crazy symbols like

    ï

  3. then I just stripped it off

    $json = str_replace(array('ï',''), '',$json);
    

    and I successfully decoded my JSON



我身边的一个问题是,有一些无效的数字从0开始,例如:“001”,“002”,“ 003“。</ p>

 ”expectedToBeReturned“:1,
”inventoryNumber“:001,
”remindNote“:”“,
</ code> </ pre>

将001替换为1,它可以正常工作。</ p>
</ div>

展开原文

原文

One problem from my side, is that there were some invalid numbers starting with 0, Ex: "001", "002", "003".

     "expectedToBeReturned":1,
     "inventoryNumber":001,
     "remindNote":"",

Replace 001 with 1 and it works.

I had same issue. For me it was causing by echo "<br/><pre>". I was trying to pass json string to another php file using exit(json_encode(utf8ize($resp_array))); At the beginning of file i had decleared break line tag... So this was error for me. Removing this break line tag , i was able to decoding my json string an other php file..

共11条数据 1 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐