【发布时间】:2020-10-12 20:04:14
【问题描述】:
我正在构建一个小型天气 API 作为练习,以使用 QML 并使用 OpenWeather 正确操作 API 调用,您可以在那里看到典型的 API 响应。
问题我无法让 API 调用正常工作。在为您在下面看到的一些城市设置了一个最小示例之后,它应该在城市旁边出现天气的象征,但它没有发生。图标列表可以在here 找到。为了完整起见,MVE 的源代码可以在here 找到。
来自编译器的错误:qrc:/main.qml:282: SyntaxError: JSON.parse: Parse error
这是正在发生的事情
这是预期的
典型的 API JSON 响应可以在 here 及以下找到:
{
"coord": {
"lon": -122.08,
"lat": 37.39
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"base": "stations",
"main": {
"temp": 282.55,
"feels_like": 281.86,
"temp_min": 280.37,
"temp_max": 284.26,
"pressure": 1023,
"humidity": 100
},
"visibility": 16093,
"wind": {
"speed": 1.5,
"deg": 350
},
"clouds": {
"all": 1
},
"dt": 1560350645,
"sys": {
"type": 1,
"id": 5122,
"message": 0.0139,
"country": "US",
"sunrise": 1560343627,
"sunset": 1560396563
},
"timezone": -25200,
"id": 420006353,
"name": "Mountain View",
"cod": 200
}
下面是与 API 调用相关的一段代码:
main.qml
// Create the API getcondition to get JSON data of weather
function getCondition(location, index) {
var res
var url = "api.openweathermap.org/data/2.5/weather?id={city id}&appid={your api key}"
var doc = new XMLHttpRequest()
// parse JSON data and put code result into codeList
doc.onreadystatechange = function() {
if(doc.readyState === XMLHttpRequest.DONE) {
res = doc.responseText
// parse data
var obj = JSON.parse(res) // <-- Error Here
if(typeof(obj) == 'object') {
if(obj.hasOwnProperty('query')) {
var ch = onj.query.results.channel
var item = ch.item
codeList[index] = item.condition["code"]
}
}
}
}
doc.open('GET', url, true)
doc.send()
}
为了解决这个问题,我查阅了几个来源,首先:official documentation 和相关函数。我相信它设置正确,但我添加了完整性参考。
我还遇到了this one,它解释了如何简单地应用XMLHttpRequest。
此外,我对问题进行了更多研究以找到解决方案,并咨询了this one,其中还解释了如何应用JSON 解析功能。但还是有些不对劲。
感谢您指出解决此问题的正确方向。
【问题讨论】:
-
没有人会下载源代码、安装图标和其他任何东西。您必须提供minimal reproducible example。如果无法访问您从中获取 JSON 的站点,请提供响应 (doc.responseText)。至于问题 - 错误很清楚,您收到的 JSON 不正确,仅此而已
-
@folibis,感谢您的光临并阅读问题,非常感谢您抽出宝贵的时间。该代码是公开的,任何想尝试的人都可以下载和测试。源代码足够小:是一个带有按钮的窗口。我亲自下载了源代码并提供了answers供其他用户尝试帮助。我在下面找到并发布了我的问题的解决方案,希望对其他人有用。
标签: c++ json qt xmlhttprequest qml