从非迭代 JSON 对象中获取值
Posted
技术标签:
【中文标题】从非迭代 JSON 对象中获取值【英文标题】:Fetch value from non-iterating JSON object 【发布时间】:2021-03-06 10:17:51 【问题描述】:我有一个无法从中获取特定值的天气预报 JSON 对象。我正在尝试从下面的 json 中获取 weather_description。
JSON
"request":
"type": "City",
"query": "New York",
"language": "en",
"unit": "m"
,
"location":
"name": "New York",
"country": "United States of America",
"region": "New York",
"lat": "40.714",
"lon": "-74.006",
"timezone_id": "America/New_York",
"localtime": "2020-11-23 10:30",
"localtime_epoch": 1606127400,
"utc_offset": "-5.0"
,
"current":
"observation_time": "03:30 PM",
"temperature": 11,
"weather_code": 122,
"weather_icons": [
"https://assets.weatherstack.com/images/wsymbols01_png_64/wsymbol_0004_black_low_cloud.png"
],
"weather_descriptions": [
"Overcast"
],
"wind_speed": 19,
"wind_degree": 340,
"wind_dir": "NNW",
"pressure": 1014,
"precip": 12,
"humidity": 77,
"cloudcover": 100,
"feelslike": 8,
"uv_index": 3,
"visibility": 16,
"is_day": "yes"
HTML
<div>this.weatherData | keyvalue </div>
TS 文件
getWeatherReport(data)
this.weatherService.getWeatherReport(data.location).subscribe(
data => this.weatherData = data; );
预期输出: 阴
实际输出: [对象对象],[对象对象],[对象对象]
【问题讨论】:
【参考方案1】:KeyValue 管道符号不适用于您的情况。所以我们必须找到所需的密钥。由于 weather_descriptions 是一个数组,因此如果有多个元素,则使用循环。这是您想要的值的 html 代码。
<div *ngIf="this.weatherData && this.weatherData.current && this.weatherData.current.weather_descriptions">
<span *ngFor= "let desc of this.weatherData.current.weather_descriptions">desc</span>
</div>
【讨论】:
现在得到预期的输出。但仍然在控制台窗口中收到以下错误 core.js:4442 ERROR TypeError: Cannot read property 'current' of undefined at DashboardComponent_Template (dashboard.component.html:9) 您可以在 div 上添加一些空检查验证。编辑了我的答案。以上是关于从非迭代 JSON 对象中获取值的主要内容,如果未能解决你的问题,请参考以下文章