【问题标题】:How to join Json response element如何加入 Json 响应元素
【发布时间】:2019-02-28 17:02:38
【问题描述】:

我正在调用 OpenWeatherApi,我正面临两难境地。我正在拉回响应,但只需要特定的数据元素。我成功地提取了某些元素,但在提取 CITY 元素时遇到了问题。

这是来自 API 调用的响应:

{
"coord": {
    "lon": -122.4,
    "lat": 45.64
},
"weather": [
    {
        "id": 800,
        "main": "Clear",
        "description": "clear sky",
        "icon": "01n"
    }
],
"base": "stations",
"main": {
    "temp": 287.5,
    "pressure": 1022,
    "humidity": 82,
    "temp_min": 284.25,
    "temp_max": 289.25
},
"visibility": 16093,
"wind": {
    "speed": 0.96,
    "deg": 10.5029
},
"clouds": {
    "all": 1
},
"dt": 1537854780,
"sys": {
    "type": 1,
    "id": 2321,
    "message": 0.0172,
    "country": "US",
    "sunrise": 1537884050,
    "sunset": 1537927234
},
"id": 420040945,
"name": "Vancouver",
"cod": 200

}

这是我需要的特定元素的映射:

const main = response.data["main"]
const sys = response.data["sys"]
const city = response.data.name;
const weather = response.data["weather"][0]
const data = Object.assign(main, weather, sys, city)
res.send(data)
console.log(data)

最后,这是我映射的响应:

{
"0": "C",
"1": "i",
"2": "n",
"3": "c",
"4": "i",
"5": "n",
"6": "n",
"7": "a",
"8": "t",
"9": "i",
"temp": 293.74,
"pressure": 1018,
"humidity": 90,
"temp_min": 293.15,
"temp_max": 294.25,
"id": 2179,
"main": "Rain",
"description": "light rain",
"icon": "10n",
"type": 1,
"message": 0.0044,
"country": "US",
"sunrise": 1537874932,
"sunset": 1537918192

}

如您所见,CITY 被拆分为单独的元素。如果我只拉 CITY,它会拉出准确的城市就好了,因为 “辛辛那提” 不是 “名称”:“辛辛那提”。

如何加入元素以形成城市,或完全重新创建“名称”:“城市”元素?

【问题讨论】:

    标签: arrays json object axios


    【解决方案1】:

    你得到了错误的结果,因为 city 是一个数组并且它正在传播。将您的代码更改为以下代码

    Object.assign({}, main, weather, sys, {city})
      or 
    Object.assign({}, main, weather, sys, {name:city})
    

    解决方法是将数组值转换为对象属性。

    【讨论】:

    • 完美。非常感谢!
    • @ChrisSimmons 您可以将答案标记为已接受,以便其他人知道您的问题已解决。
    • 是的。我必须等一分钟才能被允许检查。
    猜你喜欢
    • 2014-03-29
    • 1970-01-01
    • 2022-11-15
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多