【问题标题】:Converting GeoJSON object to Javascript Array将 GeoJSON 对象转换为 Javascript 数组
【发布时间】:2014-11-25 12:30:05
【问题描述】:

我需要将来自服务器的 GeoJSON 输出转换为 Javascript 数组;我已经进行了一些搜索,它们是针对“常规”JSON 输出而不是 GeoJSON。这是服务器的输出:

{"type":"FeatureCollection","features":[{"type":"Feature","property":"blah"}, {"type":"Feature","property":"blah2"}]}

这就是我需要的(注意,不需要对“特征”变量进行引用):

features = [{"type":"Feature","property":"blah"}, {"type":"Feature","property":"blah2"}]}

我想我需要找到 'features' 属性,然后遍历它的对象?谢谢!

【问题讨论】:

  • 所以你有一个有效的 JSON 字符串,你想把它转换成无效的东西?
  • features = JSON.parse('{"type":"FeatureCollection","features":[{"type":"Feature","property":"blah"}, {"type":"Feature","property":"blah2"}]}').features
  • 我需要将我的 javascript 代码中的某些内容转换为标准的 Javascript 数组;常规(有效)GeoJSON 在代码的其他部分中使用得很好。谢谢。
  • @Malk:我需要循环执行——不能对值进行硬编码。谢谢。

标签: javascript arrays geojson


【解决方案1】:

GeoJSON 对象仍然是 JSON 对象(这是他们的文档说的第一件事)。

http://geojson.org/geojson-spec.html

如果您想存储 GeoJSON 对象的特性 PROPERTY,请在转换为 javascript 对象后像往常一样访问属性值并将该属性推送到新变量中,或按原样使用。

var geoObject = JSON.parse(geoJSONObject);
var features = [];

features = geoObject.features;

【讨论】:

  • 嗨,谢谢。但是出现错误: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data geoObject = JSON.parse(geoJsonData);
  • 回答已接受!我想我所要做的就是: features = geoJsonData.features; [不需要 JSON.parse]。谢谢!
  • 啊,当时geoJSON对象还不是JSON,它已经是一个javascript对象了:)
  • 嘿,终于在几个小时后用这个解决方案找到了某个地方...... :-) 任何人都知道如何获取数组中的属性,我尝试了 features = geoObject.features.properties,但那没有工作。为特征数组工作,但我想更深入并获得所有属性???
  • 好的,所以我得到它以防其他人需要它:var features = [];特征 = json.features; var jproperties = json.features.map(function (el) { return el.properties; });
猜你喜欢
  • 2021-10-25
  • 2021-10-27
  • 2019-10-22
  • 1970-01-01
  • 2021-05-07
  • 2021-01-15
  • 2021-06-19
  • 2017-11-13
  • 2014-02-04
相关资源
最近更新 更多