如何解决实现json集的一个参数
我有 JavaScript 语言的代码,当我输入 console.log(event) 时,输出是:
{"type":"FeatureCollection","features":[{"type":"Feature","id":"","geometry":null,"properties":{"GRAY_INDEX":176}}],"totalFeatures":"unkNown","numberReturned":1,"timeStamp":"2021-03-03T14:04:13.362Z","crs":null}
我想要“属性”部分中的“GRAY_INDEX”值。我应该怎么办? 这是我的代码:
map.on('singleclick',function(evt) {
document.getElementById('info').innerHTML = '';
var view = map.getView();
var viewResolution = view.getResolution();
var url = UnTiled.getSource().getfeatureinfoUrl(
evt['coordinate'],viewResolution,'epsg:3857',{'INFO_FORMAT': 'application/json'}
);
console.log(url);
if (url) {
fetch(url)
.then(function (response) { return response.text(); })
.then(function (html) {
html;
console.log(html);
});
}
});
我试过了:
console.log(html["properties"]
但控制台说未定义
解决方法
如果您格式化了 json,您将能够更清楚地看到如何访问它:
{
"type": "FeatureCollection","features": [
{
"type": "Feature","id": "","geometry": null,"properties": {
"GRAY_INDEX": 176
}
}
],"totalFeatures": "unknown","numberReturned": 1,"timeStamp": "2021-03-03T14:04:13.362Z","crs": null
}
如果将上述内容分配给 html
,那么要访问 GRAY_INDEX
值,您应该这样做:
html.features[0].properties.GRAY_INDEX
您希望首先使用 response.json()
而不是 response.text()
或在尝试访问之前添加 html = JSON.parse(html)
将响应解析为 JSON。
您似乎在参数“html”中获得了 JavaScript 对象的 JSON 表示,如果是这种情况,您首先需要将 JSON 解析为对象。比您想要访问功能的属性。 Features 是一个数组,所以如果你想获取所有元素的属性,你应该这样做:
var html = '{"type":"FeatureCollection","features":[{"type":"Feature","id":"","geometry":null,"properties":{"GRAY_INDEX":176}}],"totalFeatures":"unknown","numberReturned":1,"timeStamp":"2021-03-03T14:04:13.362Z","crs":null}';
var o = JSON.parse(html);
o.features.forEach(function(each,index) {
console.log(`index = ${index}\n`,each.properties);
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。