简体   繁体   English

如何解析Haskell中的Json对象列表?

[英]How to parse a list of Json objects in Haskell?

I have a data class: 我有一个数据类:

data MyData = MyData { a :: Int, b :: String }
instance ToJSON MyData where
  ....

instance FromJSON MyData where
  ....

I can parse a single object from json: 我可以解析json中的单个对象:

get :: IO (Maybe MyData)
get = do
  res <- getSingleItemHttp
  return $ decode $ responseBody res

How can I get a list of MyData? 如何获取MyData列表?

get2 :: IO [MyData]
get2 = do
      res <- getManyItemsHttp

      --????
      return $ decode $ responseBody res -- doesn't compile

How would I go about parsing responseBody to List ? 我将如何解析responseBody到List

It should work as it is once you pass in an array (and decode as a list) so you probably just have to change your signature to get2 :: IO (Maybe [MyData]) : 传入数组(并解码为列表)后,它应该可以正常工作,因此您可能只需要将签名更改为get2 :: IO (Maybe [MyData])

{-# LANGUAGE DeriveGeneric, OverloadedStrings #-}
module Json where

import GHC.Generics
import Data.Aeson
import Data.Text
import Data.ByteString.Lazy

data MyData = MyData { a :: Int, b :: String }
  deriving (Generic, Show)

instance FromJSON MyData

example :: ByteString
example = "[{ \"a\": 1, \"b\": \"Hello\" }, { \"a\": 2, \"b\": \"World\" }]"

example

λ> decode example :: Maybe [MyData]
Just [MyData {a = 1, b = "Hello"},MyData {a = 2, b = "World"}]

your problem 你的问题

would be something like this: if you try 会是这样的:如果您尝试

get :: [MyData]
get = decode example

the compiler will complain with 编译器会抱怨

Couldn't match expected type [MyData] with actual type Maybe a0 无法将预期的[MyData]类型与实际的类型Maybe a0匹配...

which should give you a big hint. 这应该给你一个很大的提示。

You can still get your signature with Data.Maybe.maybeToList : 您仍然可以使用Data.Maybe.maybeToList获得签名:

get :: [MyData]
get = Prelude.concat . maybeToList $ decode example

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM