如何在Javascript中输出字符串作为json?

时间:2016-11-27 19:31:30

标签: javascript php json ajax

我试图将查询结果从php转换为javascript对象。所以在控制台中我看到一条错误消息未捕获的SyntaxError:意外的令牌{在位置66的JSON 。我知道这是因为我试图在变量是一个字符串时读取一个json。继承我的困境。以下是名为thestartgeom的文本列的查询结果,其中包含geojson对象(纬度和经度):

{"type":"Point","coordinates":[40.752067565918,-73.9678421020508]}
{"type":"Point","coordinates":[40.6908912658691,-73.9961242675781]}
{"type":"Point","coordinates":[40.7666969299316,-73.9906158447266]}

我将其存储为文本列的原因是因为数据库中有超过100,000条记录,我试图只选择不同的行。我知道这是一个文本列,但我想在javascript中将其作为json对象读取,因此我可以逐行进行并输出纬度和经度(40.342,-73.221)。如果我冒犯了我的问题,请原谅我,但这真让我烦恼,所以这是我的最后一招。

我的最终目标是在javascript中仅输出对象的坐标。

以下是我的代码,非常感谢任何帮助。

我的php文件:

<?php

$connect = pg_connect("host=127.0.0.1 dbname=d106 user=b16 password=cccC") or die("Could not connect: ");
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bike");
if (!$result)
{
    echo "no results ";
}

while($row = pg_fetch_array($result)) 
    $coor = $row['thestartgeom'];
    echo $coor;   
}
pg_close($connect);
 ?>

我的HTML / JS:

<html>
<head>
<title>Simple</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script>

$.ajax({
    type: "GET",
    dataType: "JSON",
    url: "getstat.php",
    data: {sataVariable: "here is some data send with GET method"},
    success: function(data) {
        var r = data.responseText;
        var j = JSON.parse(r);
        var coords = j.coordinates;

        document.writeln(coords);   // attempting to take the coordinates and store it in a variable
        for (i = 0; i < coords.length; i++) {
            coords.forEach(function(entry){     
                // loop through the coordinates and output the lat,lng
                var d = document.getElementById("fpcoords");
                d.innerHTML = d.innerHTML + "<br>" + "LatLng(" + entry[0] + "," + entry[1] +  "));"
            });

        }      
    }
});
</script>
</head>
    <body>
    </body>


   </html>

2 个答案:

答案 0 :(得分:0)

你的第一个JSON无效,三个对象需要在一个数组中,这意味着你需要用[]括起它们并用逗号分隔它们,我也会重新格式化你的JSON,只是为了限制不必要的数量数据:

<?php
$connect = pg_connect("host=127.0.0.1 dbname=d106 user=b16 password=cccC") or die("Could not connect: ");
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bike");
if (!$result){
    echo '{"error":"no results"}';
}

$points= array();    
while($row = pg_fetch_array($result)) 
    $coordinate = json_decode($row['thestartgeom'])->coordinates;
    $p = new stdClass;
    $p->lat = $coordinate[0];
    $p->long = $coordinate[1]; 
    array_push($points, $p);
}
$output = new stdClass;
$output->points = $points;
echo json_encode($output);
pg_close($connect);
?>

使用PHP Sandbox: http://sandbox.onlinephpfunctions.com/code/0d3c4081edf097190e7233dc49b3f84cbe0ed094

这将输出您的JSON:

{
 "points": [
   {
     "lat": 40.752067565918,
     "long": -73.9678421020508
   },
   {
     "lat": 40.6908912658691,
     "long": -73.9961242675781
   },
   {
     "lat": 40.7666969299316,
     "long": -73.9906158447266
   }
 ]
}

然后简单地在Javascript中迭代它们:

var dataset = /* The JSON above... */
var pointList = document.getElementById('pointList');

dataset.points.forEach(function(p){
  var li = document.createElement('li');
  li.innerHTML = "LatLong: "+p.lat+", "+p.long;
  pointList.appendChild(li);
});

一个有效的JSFiddle: https://jsfiddle.net/workingClassHacker/qkpp333z/1/

答案 1 :(得分:-1)

JSON字符串无效。服务器应返回格式正确的JSON字符串。在您的情况下,您必须将三行括在方括号[ ]中,并在每个对象后面加上逗号,

[
   {
      "type":"Point",
      "coordinates":[
         40.752067565918,
         -73.9678421020508
      ]
   },
   {
      "type":"Point",
      "coordinates":[
         40.6908912658691,
         -73.9961242675781
      ]
   },
   {
      "type":"Point",
      "coordinates":[
         40.7666969299316,
         -73.9906158447266
      ]
   }
]

此外,将来我会在将数据插入数据库之前对数据进行编码,因此您不必手动格式化输出字符串以返回有效的JSON响应。