如何从数据中获取键值

时间:2018-12-23 19:10:38

标签: haskell

我是Haskell的新手,并且想为用户解析JSON。

有这种感觉:

import Data.Aeson as Q
import Data.Text
import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Lazy as B
import Network.HTTP.Conduit (simpleHttp)
import GHC.Generics

data DataPoint = DataPoint { id :: Int
                           , description :: String
                           , icon :: String
                           } deriving (Show, Generic)

data Temperatures = Temperatures { weather :: [DataPoint]
                                 } deriving (Show, Generic)

instance FromJSON Temperatures
instance ToJSON Temperatures
instance FromJSON DataPoint
instance ToJSON DataPoint`

jsonURL :: String -> String
jsonURL q = "url here hidden"

getJSON :: String -> IO B.ByteString
getJSON town = simpleHttp (jsonURL town)

main :: IO ()
main = do
 putStrLn "Hello! Please insert your town >>> \n "
 town <- getLine
 putStrLn ("Your town is: " ++ town ++ "\n")
 d <- (eitherDecode <$> (getJSON town)) :: IO (Either String Temperatures)
 case d of
  Left e -> putStrLn "Error occured. Try again please"
  Right stuff -> putStrLn (fmap weather) $ stuff

想显示id和描述,但映射不正确的方式,是int吗? 而且可以存储这样的数据还是我应该

1 个答案:

答案 0 :(得分:1)

  

想显示ID和描述,但映射方式不正确,是整数吗?

,这不是正确的方法。

实际上,您可以使用DataPoint通过以下方式从Temperatures获取weather的列表:

weather stuff

并使用id来打印description列表中的DataPointmapM_

import Control.Monad (mapM_)
import Prelude hiding (id)

...
Right stuff -> mapM_ (\d->putStrLn (show (id d) ++ " " ++ (description d))) 
                     (weather stuff)
...

请注意,它需要从id隐藏Prelude函数。否则将发生Ambiguous occurrence错误。