[Haskell-cafe] "Flatten" JSON objects under toListOf

13 views
Skip to first unread message

Stuart Popejoy

unread,
Nov 24, 2014, 11:41:47 PM11/24/14
to haskell-cafe
Hi,

I'd like to transform some JSON to "flatten" objects in a list to a
single dimension. Say I have:

[{ "Name": "Stuart", "Dimensions": { "H": 71, "W": 170 } },
{ "Name": "Sam", "Dimensions": { "H": 72, "W": 180 } }]

How do I get it to just

[{ "Name": "Stuart", "W": 170 } },
{ "Name": "Sam", "W": 180 } }]

I've tried zipWith with various toListOf constructions to pick apart and
rebuild a new JSON object. Is there a better way?

Thanks,
Stuart
_______________________________________________
Haskell-Cafe mailing list
Haskel...@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Daniel Gorín

unread,
Nov 25, 2014, 6:15:37 AM11/25/14
to Stuart Popejoy, Haskell Cafe
I would just write a parser that picks the fields you want. You could have the parser return a Value but I’d rather collect them in a separate data-structure. For your example, one would have:

flatten :: Value -> Either String Value
flatten
= fmap reencode . parseEither extract
where
extract
= withObject "my obj" $ \o -> do
dv <- o .: "Dimensions"
flip (withObject "dim") dv $ \d ->
liftA2 (,) (o .: "Name") (d .: "W")

reencode :: (Text,Int) -> Value
reencode (n,w)
= object [ "Name" .= n, "W" .= w ]

Now you can map the flatten function over your list of of objects, find out those that were malformed, etc.
Reply all
Reply to author
Forward
0 new messages