[Haskell-cafe] "Flatten" JSON objects under toListOf
Daniel Gorín
dgorin at dc.uba.ar
Tue Nov 25 11:15:10 UTC 2014
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.
On 25 Nov 2014, at 04:41, Stuart Popejoy <spopejoy at panix.com> wrote:
> 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
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
More information about the Haskell-Cafe
mailing list