RandomB
RandomB

Reputation: 3747

ToJSON with custom representation

I have some type like

data D = D { x :: Maybe X }

and I need to serialize it to JSON like: {"x": {XXX} }, where XXX is the representation of X when x is Just X object. OK, BUT when it's Nothing it must be {}, i.e.: {"x": {}}. How to implement ToJSON instance for such D ? Conversion to String is wrong, I get "{}" instead of {}

Upvotes: 2

Views: 77

Answers (1)

hao
hao

Reputation: 10228

If I'm not misunderstanding, I think you want this:

instance ToJSON D where
    toJSON (D maybeX) =
      object ["x" .= (case maybeX of
                        Nothing -> mempty
                        Just x -> toJSON x)]

And, as you pointed out in the comments, you can golf that inner expression as maybe (Object mempty) toJSON maybeX :: Value.

Upvotes: 2

Related Questions