【问题标题】:Achieve a parameter of the json set实现一个json集的参数
【发布时间】:2021-06-02 03:32:32
【问题描述】:

我有 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"]

但控制台说未定义

【问题讨论】:

    标签: javascript json console.log


    【解决方案1】:

    如果您格式化了 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
    

    您需要先将响应解析为 JSON,方法是使用 response.json() 而不是 response.text() 或在尝试访问之前添加 html = JSON.parse(html)

    【讨论】:

      【解决方案2】:

      您似乎在参数“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);
      });

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-08
        • 1970-01-01
        • 2018-08-11
        • 2023-03-05
        相关资源
        最近更新 更多