gpt4 book ai didi

haskell - Aeson:如何解析带有字符串化对象元素的对象?

转载 作者:行者123 更新时间:2023-12-02 18:07:16 24 4
gpt4 key购买 nike

我需要解析一个具有字符串元素的对象,其中字符串本身是一个字符串化对象:

{ 
"a" : "apples",
"bar" : "{\"b\":\"bananas\"}"
}

我想将其解析为 Just ( Foo { fooA = "apples", fooBar = Bar { barB = "bananas"} } ) 所以如果解析 bar 返回 Nothing 然后整个对象的解析返回 Nothing,即结果就像对象的 bar 元素没有被字符串化。

这是我的尝试,其中 testData 的解析返回 Nothing:

{-# LANGUAGE OverloadedStrings #-}

module Main where

import Data.Aeson
import Data.Aeson.Types

data Foo = Foo { fooA :: String
, fooBar :: Bar
} deriving (Show)

instance FromJSON Foo where
parseJSON (Object o) = do bar <- (o .: "bar")
Foo <$> o .: "a" <*> parseJSON bar
parseJSON x = typeMismatch "Foo" x

data Bar = Bar { barB :: String
} deriving (Show)

instance FromJSON Bar where
parseJSON (Object o) = Bar <$> o .: "b"
parseJSON x = typeMismatch "Bar" x

testData = "{ \"a\":\"apples\", \"bar\":\"{\\\"b\\\":\\\"bananas\\\"}\" }"

main :: IO ()
main = putStrLn $ show d
where d :: Maybe Foo
d = decode testData

如何修改上述代码以更接近我的需要?

最佳答案

您可以使用以下方法更深入地了解正在发生的情况:

main = print (eitherDecode testData :: Either String Foo)

显示:Left“$ 中的错误:预期的栏,遇到字符串”

在此代码中:

 parseJSON (Object o) = do bar <- (o .: "bar")
Foo <$> o .: "a" <*> parseJSON bar

barString ... 值。

要完成您想要做的事情,您可以向 Bar 的 FromJSON 实例添加一个案例来捕获此内容:

instance FromJSON Bar where
...
parseJSON (String text) =
case eitherDecode (textToLBS text) of
Left e -> fail $ "while decoding a Bar: " ++ e
Right b -> return b
...

或者您可以将此代码放入 Foo 的 parseJSON 定义中。

此处 textToLBS 将严格的文本转换为惰性字节字符串:

import qualified Data.Text as T
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Text.Encoding as TE

textToLBS :: T.Text -> LBS.ByteString
textToLBS t = LBS.fromStrict (TE.encodeUtf8 t)

代码位于:http://lpaste.net/143183

关于haskell - Aeson:如何解析带有字符串化对象元素的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33183703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com