javascript - "SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 295 of the JSON data"

标签 javascript php json mysqli

我正在列出健身房的 list ,其中包括名称、图像、团队、地点、cp、所有者、id、纬度、经度。

现在我知道它可以获取每个查询等。但它现在提供了许多相同的 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

长度:5.054567

最佳答案

您在结果集的每次迭代中都echo-ing 一个完整的JSON 对象。这将使响应无效。

简单地移动

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

while循环之外并将$encode赋值更改为push...

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

这将导致数组响应。

关于javascript - "SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 295 of the JSON data",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46107433/

相关文章:

javascript - 动态添加字段到 Formik 表单

php - Laravel 和 MySQL 时间戳值随 mysqld 配置而变化

json - Scala:将案例类序列化为 JSON ,备用名称

java - 使用 PrintWriter 对象将 List 对象从 Java Servlet 发送到 JSP?

java - 使用适配器时<和>符号有什么用?

javascript - AWS 网关超时

javascript - 如何迭代selenium中的每个文本字段?

javascript - 如何弹出一个选择列表,并用选择更新站点?

php - 在php脚本中执行mysql的最佳方法

php - 内部连接和同一查询中的 where 返回空白错误 mysql