从 URL 获取 json 并显示特定数据

Getting json from an URL and displaying specific data

我在反向地理编码方法中尝试从 URL 获取 json 时遇到问题: 我根据在 Whosebug 上找到的解决方案进行了尝试。 当我尝试在警报中显示 json 时,它显示:undefined

adressReverseGeoCode(item: any, elementId: any) {
var getJSON = (url: any, callback: any) => {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'json';
  xhr.onload = () => {
    var status = xhr.status;
    if (status == 200) {
      callback(null, xhr.response);
    } else {
      callback(status);
    }
  };
  xhr.send();
};

getJSON('http://nominatim.openstreetmap.org/reverse?format=json&lat=' + item.latitude + '&' + 'lon=' + item.longitude + '&addressdetails=1',
  (err: any, data: any) => {
    if (err != null) {
      alert('Something went wrong: ' + err);
    } else {
      alert(data.result);
    }

  });

}

我想从 json 中获取 "display_name",以便稍后将其放入文本输入中。 您可以尝试此 link 来查看 json 文件

{
 "place_id":"154253419",
 "licence":"Data © OpenStreetMap contributors, ODbL 1.0. http:\/\/www.openstreetmap.org\/copyright",
 "osm_type":"way",
 "osm_id":"424211755",
 "lat":"-23.56183",
 "lon":"-46.6598392",
 "display_name":"Alameda Ministro Rocha Azevedo, Jardim Paulista, São Paulo, Microrregião de São Paulo, RMSP, Mesorregião Metropolitana de São Paulo, São Paulo, Southeast Region, 01410-001, Brazil",
 "address":{"road":"Alameda Ministro Rocha Azevedo","suburb":"Jardim Paulista","city_district":"Jardim Paulista","city":"São Paulo","county":"Microrregião de São Paulo","state_district":"Mesorregião Metropolitana de São Paulo","state":"São Paulo","postcode":"01410-001","country":"Brazil","country_code":"br"},
 "boundingbox":["-23.5642064","-23.5601209","-46.662319","-46.6580485"]
}

提前感谢您能给我的任何帮助!

没有data.result!这就是为什么它是未定义的。你的数据是JSON。所以就做 data.display_name。可能吧!

var obj = JSON.parse(data); // as suggested by @charlietfl
console.log(obj.display_name);
alert(obj.display_name);