【问题标题】:JSON is valid, but JSON.parse(jsonObject) return errorJSON 有效,但 JSON.parse(jsonObject) 返回错误
【发布时间】:2016-01-09 08:12:51
【问题描述】:

我使用 Yii 框架编写网站。我需要从 Yii 中的数据库中获取所有数据,为此我编写了一些代码:

var response = 
    <?php 
        function getAllDataTable() {
            $connection = Yii::app()->db;
            $sql = "SELECT * FROM data";
            $command = $connection->createCommand($sql);

            $rows = $command->queryAll();

            return $rows;
        }

        function getJsonFromRows($rows) {
            $json = "{ ";

            foreach ($rows as $rowIndex => $rowData) {
                if ($rowIndex !== 0)
                    $json .= ", ";

                $json .= "\"row".$rowIndex."\": {";

                $colIndex = 0;
                foreach ($rowData as $columnHeader => $cellValue) {
                    if ($colIndex++ !== 0)
                        $json .= ", ";
                    $json .= "\"".$columnHeader."\"".": "."\"".$cellValue."\"";
                }

                $json .= "} ";
            }

            $json.="}";

            return $json;
        }

        $rows = getAllDataTable();

        echo getJsonFromRows($rows);
     ?>;

var data = JSON.parse(response);

console.log("data: \"" + data + "\"");

我尝试使用 JSON 来做到这一点。 这是来自调试器的代码:

var response = { "row0": {"year": "2001", "discipline": "some discipline", "theme": "some theme", "pair": "some pair"} , "row1": {"year": "2001", "discipline": "some discipline", "theme": "some theme", "pair": "some pair"} };
var data = JSON.parse(response);
console.log("data: \"" + data + "\"");

这是我得到的错误:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data material:53:18

Using //@ to indicate sourceMappingURL pragmas is deprecated. Use //# instead jquery-1.9.1.min.js:1:0

Use of getPreventDefault() is deprecated.  Use defaultPrevented instead.

我在许多网站上检查 php 脚本的结果,例如: https://jsonformatter.curiousconcept.com/ 我的 json 对象是正确的,但 JSON.parse(jsonObject) 返回错误。为什么?

附:这个主题不是重复的,我看到了所有这些帖子: JSON Lint says it's valid but JSON.parse throws error jQuery IE9 JSON.SyntaxError parseerror, but JSON is valid JSON.parse Error on Valid JSON check if required JSON is valid - node JSON.parse error on a seemingly valid JSON

【问题讨论】:

  • 有效或无效。 JSON Lint 真的 说它是有效的,然后你使用不同的数据。回到(并纠正)假设:JSON 是文本。在显示的代码中,没有 JSON,而是分配了一个 JavaScript 对象字面量。
  • 另外,不要手动创建 JSON/XML/等。至少在某些时候或使用某些数据,您肯定会弄错。

标签: javascript php json yii


【解决方案1】:

JSON.parse 期望将字符串作为第一个参数传递。

换句话说,您已经有一个 javascript 对象。如果您有一个 string 并且想要转换为 JavaScript 对象,则使用 JSON 解析。

【讨论】:

    【解决方案2】:

    您将对象而不是字符串传递给 JSON.parse。考虑一下您是否甚至需要解析它,因为您的 var response 可能已经是您想要的对象。

    【讨论】:

      【解决方案3】:

      在 PHP 中

          function getJsonFromRows($rows) {
              $json = array();
      
              foreach ($rows as $rowIndex => $rowData) {
                  $tmp = array();
                  foreach ($rowData as $columnHeader => $cellValue) {
                      $tmp[$columnHeader] =$cellValue;
                  }
      
                  $json["$rowIndex"] = $tmp;
              }
      
              return json_encode($json);
          }
      

      现在,如果您将对响应执行 JSON.parse,它将转换。

      【讨论】:

        【解决方案4】:

        正如其他人所说,您正在尝试解析一个对象。

        JSON.stringify() 将对象转换为字符串。 JSON.parse() 将 JSON 字符串转换为对象。

        这是一个小提琴,显示您的代码就是这种情况。 http://jsfiddle.net/wpwelch/39hx5oy0/

        <div id="jsonString"></div>
        <br />
        <div id="jsObject"></div>  
        
         var test = { "row0": {"year": "2001", "discipline": "some discipline", "theme": "some theme", "pair": "some pair"} , "row1": {"year": "2001", "discipline": "some discipline", "theme": "some theme", "pair": "some pair"} };
            strEcho = JSON.stringify(test);
            objRef = test.row0.year; // Works because var test is already an object
            $("#jsonString").html(strEcho); // Works because .stringify() is working with a valid JSON object.
            $("#jsObject").html(objRef); // This shows the year 2001
        

        在您的代码中,您可以编辑这一行

        var data = JSON.parse(response);
        

        成为

        var data = response;
        

        因为你已经有了一个有效的对象,所以一切都会正常工作。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-11-12
          • 2018-09-02
          • 1970-01-01
          • 1970-01-01
          • 2018-06-04
          相关资源
          最近更新 更多