如何解析parseJSON的数据?

时间:2016-02-24 04:52:32

标签: haskell

我有一个数据,我想从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?

1 个答案:

答案 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做了什么

但它应该是你弄明白的开始