I have JSON
that contains an encoded JSON
as string in one of its properties:
{
"firstName": "Frederick",
"lastName": "Krueger",
"address": "{\"street\": \"Elm Street, 13\", \"city\": \"Springwood\", \"state\": \"OH\"}"
}
Given that I have a data type:
data Address = Address { street :: String, city :: String, state :: String }
deriving (Generic, Show)
data Person = Person { firstName :: String, lastName :: String, address :: Address }
deriving (Generic, Show)
How do I implement FromJSON
for Person
?
One way of doing this is by writing your own parser with the function
withObject
. In that function you explicitly handle your address case. Example:These are the necessary import I had to do:
Note that in your code, you may want to avoid the partial function
fromJust
. A sample way of decoding your JSON string when it is stored in a file namedadd.json
:Output on execution: