javascript - 如何在 JSON 中访问此对象
问题描述
我正在尝试weather
在 Javascript 中访问该对象。我试过output.weather
但它返回undefined
。我究竟做错了什么?
JSON:
[
{
"location":{
"name":"XX",
"zipcode":"XX",
"lat":"42.284",
"long":"-82.029",
"timezone":"-4",
"alert":"",
"degreetype":"C",
"imagerelativeurl":"http://blob.weather.microsoft.com/static/weather4/en-us/"
},
"current":{
"temperature":"2",
"skycode":"31",
"skytext":"Clear",
"date":"2020-04-03",
"observationtime":"23:45:00",
"observationpoint":"N0P 1E0, ON",
"feelslike":"1",
"humidity":"84",
"winddisplay":"6 km/h North",
"day":"Friday",
"shortday":"Fri",
"windspeed":"6 km/h",
"imageUrl":"http://blob.weather.microsoft.com/static/weather4/en-us/law/31.gif"
},
"forecast":[
{
"low":"2",
"high":"9",
"skycodeday":"31",
"skytextday":"Clear",
"date":"2020-04-03",
"day":"Friday",
"shortday":"Fri",
"precip":"0"
},
{
"low":"2",
"high":"11",
"skycodeday":"32",
"skytextday":"Sunny",
"date":"2020-04-04",
"day":"Saturday",
"shortday":"Sat",
"precip":"60"
},
{
"low":"0",
"high":"8",
"skycodeday":"30",
"skytextday":"Partly Sunny",
"date":"2020-04-05",
"day":"Sunday",
"shortday":"Sun",
"precip":"60"
},
{
"low":"5",
"high":"11",
"skycodeday":"30",
"skytextday":"Partly Sunny",
"date":"2020-04-06",
"day":"Monday",
"shortday":"Mon",
"precip":"30"
},
{
"low":"9",
"high":"13",
"skycodeday":"26",
"skytextday":"Cloudy",
"date":"2020-04-07",
"day":"Tuesday",
"shortday":"Tue",
"precip":"80"
}
]
}
]
JS代码:
const rl = require('readline-sync');
const weather = require('weather-js');
var zipCode = rl.question('Please enter your ZIP code: ').toLowerCase();
var output;
weather.find({search: zipCode, degreeType: 'F'}, function(err, result) {
if (err)
{
console.log(err);
}
output = JSON.stringify(result);
console.log(output.weather); // returns undefined
});
解决方案
问题是输出是一个字符串,而不是一个对象。你的意思是 JSON.parse() 吗?从字符串中输出一个对象。
推荐阅读
- java - 两个 javafx Integer Spinner 双向绑定:为什么绑定不可靠?
- python-3.x - 使用 AsyncSSH 从多台计算机收集文件
- python - 使用 Django ReST api 将 100+GB 的数据从数据库表传输到 UI
- reactjs - 我如何使这个手风琴响应并以页面为中心?
- python - python sqlite3 部分搜索
- mysql - 从另一个表 MySQL 更新行设置唯一值
- ios - 如何在反应离子应用程序中将 ios 键盘返回按钮更改为下一步/完成?
- react-native - 在`Firestore`中存储常量值的最佳方法是什么?
- android - 打开选择图像意图时出现 TransactionTooLargeException(Kotlin,Android)
- windows - 绑定 0.0.0.0:6543 失败:端口已分配(不是)