我有一个数据,我想从json解析:
data MyData = MyData
{ myDataId :: UUID
, myDataVar1 :: Bool
, myDataVar2 :: Maybe (UUID, String)
}
instance FromJSON MyData where
parseJSON (Object v) =
MyData <$> v .: "id"
<*> v .: "var1"
<*> ((,) <$> ((v .: "var2") >>= (.: "id")) <*> ((v .: "var2") >>= (.: "name"))) --- ??? doesn't work
如何解析myDataVar2?
答案 0 :(得分:1)
这基于怀疑 JSON @zeta给出了@dfeuer的想法
这是一个编译/工作示例
{-# LANGUAGE OverloadedStrings #-}
module ParseJson where
import Data.Aeson
import Data.Text
import Data.Text.Encoding
import Data.ByteString.Lazy (fromStrict)
testData :: Text
testData = "{ \"id\" :\"A211MNLR\", \"var1\": false, \"var2\": { \"id\": \"GA23210X\", \"name\": \"child\"} }"
testData2 :: Text
testData2 = "{ \"id\" :\"GA23210X\", \"var1\": false, \"var2\": null}"
data MyData = MyData
{ myDataId :: Text
, myDataVar1 :: Bool
, myDataVar2 :: Maybe (Text, Text)
} deriving Show
instance FromJSON MyData where
parseJSON (Object v) =
MyData <$> v .: "id"
<*> v .: "var1"
<*> (v .:? "var2" >>= parsePair)
where parsePair (Just (Object o)) = Just <$> ((,) <$> o .: "id" <*> o.: "name")
parsePair _ = pure Nothing
parse :: Text -> Maybe MyData
parse = decode . fromStrict . encodeUtf8
这是测试:
λ> parse testData
Just (MyData {myDataId = "A211MNLR", myDataVar1 = False, myDataVar2 = Just ("GA23210X","child")})
λ> parse testData2
Just (MyData {myDataId = "GA23210X", myDataVar1 = False, myDataVar2 = Nothing})
Text
而不是UUID
- 据我所知,fromText
包中有一个uuid
可以用来进一步转换它(但它& #39; sa Maybe UUID
或者你可以为它编写FromJSON
个实例 - 遗憾的是我没时间做对了 - 抱歉:( parsePair
做了什么但它应该是你弄明白的开始