Search code examples
jsonhaskellhaskell-lensaeson

Haskell & JSON - dealing with null


I'm fairly new to Haskell and have been using Wreq to interact with a JSON API. I'm having an issue trying to edit a JSON response before submitting it back to the API. I think the problem lies with an undefined Bool.

In short, the Wreq response body in ByteString form looks like:

"{\"a\":1, \"b\":null}"

b is actually a boolean but the API response leaves it as null. I'm trying to use Lens functionality to edit it but with no success. The issue is easily reproduced in GHCI:

> import qualified Data.ByteString.Lazy as LB
> bstr = "{\"a\":1, \"b\":null}" :: LB.ByteString
> print $ bstr & key "b" . _Bool .~ True
"{\"a\":1,\"b\":null}"

Nothing is changed. What am I missing here?


Solution

  • The problem is that the _Bool prism only works when the value at key "b" is either True or False, not when it's Null. In essence, you're trying to change the type of the value from Null to Bool.

    Probably, you want to use the _Primitive prism instead. Something like:

    bstr & key "b" . _Primitive .~ BoolPrim True
    

    Keep in mind that this will change any value, not just Bools or Nulls into True. If you want to be a little more selective, you could do something like:

    bstr & key "b" . _Primitive %~ (\b -> case b of
      NullPrim -> BoolPrim True
      _ -> b)