【问题标题】:Traversing JSON in Haskell with wreq - key issues使用 wreq 在 Haskell 中遍历 JSON - 关键问题
【发布时间】:2018-01-30 16:42:37
【问题描述】:

我正在尝试遍历从 OpenWeatherMap API 获得的一些 JSON 响应,但在检索一些值时遇到了一些问题。这是我的代码:

{-# LANGUAGE OverloadedStrings #-}

import Control.Lens
import Data.Aeson.Lens (_String, key)
import Network.Wreq

myAPIKey :: String
myAPIKey = "my_api_key_here"

conditionsQuery :: String -> String -> String -> String
conditionsQuery city country key = 
   "https://api.openweathermap.org/data/2.5/forecast?q=" ++ city ++ "," ++ country ++ "&appid=" ++ key

main = do
    print "What's the city?"
    city <- getLine
    print "And the country?"
    country <- getLine

    r <- get (conditionsQuery city country myAPIKey)

    print $ r ^. responseBody . key "name" . _String
    print $ r ^. responseBody . key "cod" . _String
    print $ r ^. responseBody . key "id" . _String

问题是只返回“cod”的值(在这种情况下为“200”)。如果我们尝试使用 London,GB, Chicago, US(例如),“name”和“id”的值显示为 ""。然而响应正文看起来像:

{
   ...
   "id": 2643743,
   "name": "London",
   "cod": 200
}

我最初认为这是类型不匹配,但 200 是 Int 那里(除非我弄错了?)所以我不确定问题出在哪里? "" 似乎表明这两个键(idname)不存在,但它们确实存在。

有什么想法吗?提前致谢。

【问题讨论】:

    标签: json haskell traversal wreq


    【解决方案1】:

    响应正文看起来不像。

    根据https://openweathermap.org/forecast5,键"cod"出现在JSON对象的最外层,但"id""name"没有。

    {
        "city":{
            "id":1851632,
            "name":"Shuzenji",
            ...
            }
        "cod":"200",
        ...
    }
    

    【讨论】:

    • 很好,谢谢!但是,如果我们看这个:openweathermap.org/current,“name”和“id”都出现在最外层...
    • @DavidB。按城市ID查询时,“name”和“id”出现在最外层;当按城市名称查询时,它们不存在......我不会设计这样的 API :(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多