JSON解析JSONLint上的错误

时间:2014-12-08 01:11:32

标签: javascript json parsing object

我有这个JSON输出:

 {
  "title": "test1",
  "status": "private",
  "markers": "\"[{\"k\":48.28319289548349,\"B\":1.494140625},{\"k\":44.024421519659334,\"B\":20.302734375},{\"k\":47.517200697839414,\"B\":40.517578125},{\"k\":53.9560855309879,\"B\":23.73046875},{\"k\":49.66762782262194,\"B\":3.251953125}]\""
 }

 {
  "title": "test2",
  "status": "public",
  "markers": "\"[{\"k\":48.574789910928864,\"B\":10.546875},{\"k\":43.19716728250127,\"B\":12.48046875}]\""
 }

在JSONLint上我收到此错误:

 Parse error on line 5:
 ...":3.251953125}]\""}{    "title": "test
 ----------------------^
 Expecting 'EOF', '}', ',', ']'

以下是获取JSON对象的PHP代码:

 if ($bdd = mysqli_connect('localhost', '', '', _BDD_NAME_)) {
    $sql = 'SELECT * FROM `trip`';
    $result = mysqli_query($bdd, $sql);

    if ($result) {
        while  ($row = $result->fetch_assoc()) {
            echo json_encode(array('title'   => stripslashes($row['title']),
                                   'status'  => stripslashes($row['status']),
                                   'markers' => stripslashes($row['markers'])));
        }
    }
    else {
        echo json_encode(array('status' => 'failure'));
    }
}

 if ($bdd) {
    mysqli_close($bdd);
}

有人可以帮我识别这个JSON对象中的错误吗?

1 个答案:

答案 0 :(得分:2)

由于此处JSON中有多个对象,因此必须将它们包装在数组文字中。您还忘记了JSON对象之间的逗号:

[
     {
      "title": "test1",
      "status": "private",
      "markers": "\"[{\"k\":48.28319289548349,\"B\":1.494140625},{\"k\":44.024421519659334,\"B\":20.302734375},{\"k\":47.517200697839414,\"B\":40.517578125},{\"k\":53.9560855309879,\"B\":23.73046875},{\"k\":49.66762782262194,\"B\":3.251953125}]\""
     },
     {
      "title": "test2",
      "status": "public",
      "markers": "\"[{\"k\":48.574789910928864,\"B\":10.546875},{\"k\":43.19716728250127,\"B\":12.48046875}]\""
     }
]