json 数据未显示在传单地图上

问题描述 投票:0回答:1

我可以使用 获得 php 响应

$("#resultTable").html(response) 

导致 json 如下:

{
  "type": "FeatureCollection",
  "features": [
    "[{\"type\":\"Feature\",\"geometry\":{\"type\": \"Point\",\"coordinates\":[144.88492596994729,-37.630939830943923]},\"properties\":{\"id\":6.680000000000000e+002,\"eno\":\"E1421\",\"start_yr\":2.023000000000000e+003,\"sch_sex\":\"CO-ED\",\"psx\":\"P\",\"sch_level\":\"Primary\"}},{\"type\":\"Feature\",\"geometry\":{\"type\": \"Point\",\"coordinates\":[145.33476983598635,-38.138394865105511]},\"properties\":{\"id\":6.720000000000000e+002,\"eno\":\"E4049\",\"start_yr\":2.025000000000000e+003,\"sch_sex\":\"CO-ED\",\"psx\":\"P\",\"sch_level\":\"Primary\"}},{\"type\":\"Feature\",\"geometry\":{\"type\": \"Point\",\"coordinates\":[145.36314683445636,-38.107667866900812]},\"properties\":{\"id\":6.710000000000000e+002,\"eno\":\"E4048\",\"start_yr\":2.024000000000000e+003,\"sch_sex\":\"CO-ED\",\"psx\":\"P\",\"sch_level\":\"Primary\"}},{\"type\":\"Feature\",\"geometry\":{\"type\": \"Point\",\"coordinates\":[144.6851299838919,-37.8237898186311]},\"properties\":{\"id\":6.600000000000000e+002,\"eno\":\"E1416\",\"start_yr\":2.024000000000000e+003,\"sch_sex\":\"CO-ED\",\"psx\":\"P\",\"sch_level\":\"Primary\"}}]"
  ]
} 

为了检查这是否是一个有效的 json,我将上面的文本(字符串)保存为一个 geojson 文件并在 https://jsonformatter.org/ 中检查它的有效性它返回为有效的 json。 似乎一切都很好。但是,当我将 response 输出转换为 json 对象以显示在传单地图上时,它会抛出错误Uncaught SyntaxError:JSON 位置 2362 后出现意外的非空白字符。 在地图中显示geojson的部分代码如下:

       var queryLayer=L.geoJSON(JSON.parse(response)).addTo(mymap);

我期待 json 功能显示在地图上。 非常感谢任何帮助。

json ajax leaflet geojson
1个回答
0
投票

你的

features
奇怪的是一个字符串数组,而不是一个 GeoJSON 特征数组。所以它是有效的 JSON,但无效的 GeoJSON。您可以使用专门用于 GeoJSON 的 lint 工具,例如https://geojsonlint.com/

那个字符串似乎代表了应该直接存在的特征数组。

如果你的样本是第一次

JSON.parse
之后的结果,那么你可以这样做:

const data = JSON.parse(response); // 1st parse
data.features = JSON.parse(data.features[0]); // 2nd parse to convert the string into a proper JS array

// Then you can use the GeoJSON object
L.geoJSON(data);
© www.soinside.com 2019 - 2024. All rights reserved.