2017-05-29 110 views
0

我有一个(可能)愚蠢的问题,但我不能错过什么是...
我请求一个AWS API网关URL,我有一个json格式的响应,我解析它,但是当我想要获取特定JSON元素的值时,我会得到“undefined”而不是元素的值。JSON解析问题与Javascript

这里是我的代码:

var xhr = new XMLHttpRequest(); 
    xhr.onreadystatechange = function() { 
     if (xhr.readyState == XMLHttpRequest.DONE) { 
      jsonData = JSON.parse(xhr.responseText); 
      data = jsonData.coord; 
      document.write(data); 
     } 
    } 
    xhr.open('GET', "https://[mon-url]", true); 
    xhr.send(); 

的API响应使用

jsonData = JSON.parse(xhr.responseText) 
document.write(jsonData) 

给下面的输出解析:

{ 
    "coord": { 
    "lon": 2.35, 
    "lat": 48.85 
    }, 
    "weather": [ 
    { 
     "id": 800, 
     "main": "Clear", 
     "description": "clear sky", 
     "icon": "01n" 
    } 
    ], 
    "base": "stations", 
    "main": { 
    "temp": 291.97, 
    "pressure": 1019, 
    "humidity": 56, 
    "temp_min": 288.15, 
    "temp_max": 295.15 
    }, 
    "visibility": 10000, 
    "wind": { 
    "speed": 3.1, 
    "deg": 60 
    }, 
    "clouds": { 
    "all": 0 
    }, 
    "dt": 1495747800, 
    "sys": { 
    "type": 1, 
    "id": 5615, 
    "message": 0.0022, 
    "country": "FR", 
    "sunrise": 1495684591, 
    "sunset": 1495741168 
    }, 
    "id": 2988507, 
    "name": "Paris", 
    "cod": 200 
} 

但是,如果我试图得到一个特定的元素值,例如使用document.write(jsonData.coord)我得到"undefined"作为值。

有人能帮我理解为什么我无法正确解析我的JSON数据吗?

谢谢!

+0

你还可以记录'jsonData'的类型吗? 'console.log(typeof(jsonData))' – Rajesh

+0

@prasad,如果数据OP添加的格式正确,不应该有任何区别 –

+0

使用'jsonData = JSON.parse(JSON.stringify(xhr.responseText))' – farhadamjady

回答

1

你是从服务器获取的数据是JSON数据的字符串。您应该更改返回的响应方式,或者您必须解析JSON两次。

var xhr = new XMLHttpRequest(); 
xhr.onreadystatechange = function() { 
    if (xhr.readyState == XMLHttpRequest.DONE) { 
     jsonData = JSON.parse(xhr.responseText); 
     jsonData = JSON.parse(jsonData); 
     data = jsonData.coord; 
     document.write(data); 
    } 
} 
xhr.open('GET', "https://[mon-url]", true); 
xhr.send(); 
+1

这是一个正确的结论,事实证明'document.write(jsonData)'打印了一个JSON字符串而不是'[object Object]' –

+0

好吧,它现在可以工作了,非常感谢解释! –

0

使用JSON.parse如果响应是一个字符串