I need to parse an object that has a string element where the string itself is a stringified object:
{
"a" : "apples",
"bar" : "{\"b\":\"bananas\"}"
}
I would like to parse this into Just ( Foo { fooA = "apples", fooBar = Bar { barB = "bananas" } } )
so if parsing of bar
returns Nothing
then the parsing of the whole object returns Nothing
, ie the result is as though the bar
element of the object was not stringified.
Here is my attempt in which the parsing of testData
returns 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
How can I modify the above code to perform closer to what I need?