2

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?

Al_M
  • 63
  • 6
  • 1
    ? B is obviously not a boolean, because if it was a boolean then it would be true or false. – user253751 Dec 18 '20 at 14:57
  • 1
    Maybe you should treat the value as a `Maybe Bool` rather than a `Bool`, using something like `fromMaybe b` to either extract a boolean value or replace `null` with a default value `b`. – chepner Dec 18 '20 at 15:26

1 Answers1

3

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)
DDub
  • 3,884
  • 1
  • 5
  • 12