【问题标题】:"SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 295 of the JSON data"“SyntaxError:JSON.parse:JSON 数据第 1 行第 295 列的 JSON 数据后出现意外的非空白字符”
【发布时间】:2018-02-16 20:18:36
【问题描述】:

我正在列出健身房的名单,包括他们的姓名、形象、团队、地点、cp、所有者、id、lat、lon。

现在我知道它可以获取每个查询等,但它现在提供了许多相同的 id、图像、团队等,但它需要显示所有 mon_cp mon_owner、mon_id,因为这些 mon_* 每次都是不同的。

它还向我显示错误:“SyntaxError:JSON.parse:JSON 数据第 1 行第 295 列的 JSON 数据后出现意外的非空白字符”

    $sql = "SELECT 
f.id, f.lat, f.lon, f.name, f.url, d.fort_id, d.pokemon_id, d.owner_name, d.cp, s.fort_id, s.team, s.slots_available
FROM forts AS f
LEFT JOIN gym_defenders AS d ON f.id=d.fort_id
LEFT JOIN fort_sightings AS s ON f.id=s.fort_id ORDER BY last_modified DESC";
$result = $mysqli->query($sql);

while($row = $result->fetch_assoc()) {

    $url = preg_replace("/^http:/i", "https:", $row['url']);

    if($row['team'] == 1){ $team = "mystic";}
    if($row['team'] == 2){ $team = "valor";}
    if($row['team'] == 3){ $team = "instinct";}

        $encode = array("id" => $row['id'],
            "name" => $row['name'],
            "image" => $url,
            "team" => $team,
            "spots" => $row['slots_available'],
            "mon_cp" => $row['cp'],
            "mon_owner" => $row['owner_name'],
            "mon_id" => $row['pokemon_id'],
            "lat" => $row['lat'],
            "lng" => $row['lon']);

        echo json_encode($encode, JSON_FORCE_OBJECT);
}

需要输出以下内容:

名称:体育馆名称

图片:https://images.com/image.png

团队:勇气

mon_cp: 1234, 233

mon_owner: monowner2000,monowner232

mon_id: 150, 155

纬度:34.67854

lon: 5.054567

【问题讨论】:

  • 你在echo-ing 一个完整的 JSON 对象,每次迭代你的结果集。这将使响应无效
  • 我应该如何处理它,因为如果我在 while 循环的 } 下面回显它,它只会显示 1 项。 @菲尔

标签: javascript php json mysqli


【解决方案1】:

你是echo-ing 一个完整的 JSON 对象,每次迭代你的结果集。这将使响应无效。

简单移动

echo json_encode($encode); // note, do NOT use JSON_FORCE_OBJECT

while 循环之外并将$encode 分配更改为推送...

$encode[] = ['id' => ...

这将产生一个数组响应。

【讨论】:

  • 这确实让我的错误消失了,但它现在向我展示了这么多项目看起来我的示例输出需要如何。它现在提供了数百个具有相同信息的项目。他们只有在拥有更多值时才需要其他值,因此您可以将列表合二为一。像 mon_owner: monowner2000, monowner3
  • @PrizenTV 对不起,你说的没有多大意义。如果您的查询返回的结果太多,那么您应该将其更改为只返回您想要的数据
  • 就我而言,它只需要显示 7 个项目,因为我只有 7 个健身房,但它给了我 9999 个项目。
  • imgur.com/a/VyaIG 您会看到相同的 id,只有其中一些具有不同的 mon_* 值,这些值需要在 1 中。在图像中您会看到许多 id:5 和 1 id:9。
  • @PrizenTV 似乎你的数据库有重复的值。那和/或您的gym_defenders 和/或fort_sightings 表是多对一forts 在这种情况下,使用连接时预计会重复forts
猜你喜欢
  • 2014-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多