我是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吗? 而且可以存储这样的数据还是我应该
答案 0 :(得分:1)
想显示ID和描述,但映射方式不正确,是整数吗?
是,这不是正确的方法。
实际上,您可以使用DataPoint
通过以下方式从Temperatures
获取weather
的列表:
weather stuff
并使用id
来打印description
列表中的DataPoint
和mapM_
,
import Control.Monad (mapM_)
import Prelude hiding (id)
...
Right stuff -> mapM_ (\d->putStrLn (show (id d) ++ " " ++ (description d)))
(weather stuff)
...
请注意,它需要从id
隐藏Prelude
函数。否则将发生Ambiguous occurrence
错误。