我有一个(可能)愚蠢的问题,但我不能错过什么是...
我请求一个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数据吗?
谢谢!
你还可以记录'jsonData'的类型吗? 'console.log(typeof(jsonData))' – Rajesh
@prasad,如果数据OP添加的格式正确,不应该有任何区别 –
使用'jsonData = JSON.parse(JSON.stringify(xhr.responseText))' – farhadamjady