实现json组的一个参数

Achieve a parameter of the json set

我有 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);
});