I am getting a json response from an API endpoint that is something like this:
{
"items": [
{
"key": "",
"groupReference": "mastercard-XXXXXXXXXXXXXXX",
"type": "firstPresentment-dms",
"created": "2023-01-27T10:07:56.038Z",
"entry": 1,
"isCorrection": false,
"reportingFor": "0000",
"network": "mastercard",
"fundsTransferDate": "2023-01-27",
"fundsTransferBookDate": "2023-01-27",
}
]
}
I have used decode_json() to decode this. The problem is since the isCorrection is a pure perl boolean value, the decoding doesn’t work properly and I get this
Reference of JSON::PP::Boolean$VAR1 = bless( do{(my $o = 0)}, 'JSON::PP::Boolean' );
Any idea how to fix this issue?
2
Answers
Oh, but it does. The documentation for the mapping from JSON to Perl includes this:
So if you treat the value you get as a boolean, everything will Just Work:
Things will only go wrong if you break encapsulation and start expecting specific values there. But you can probably fix that using OO version of the interface and the
boolean_values()
orcore_bools()
methods.What you see is how it is supposed to work. This way, if you re-encode that as JSON, you get the right JSON boolean values and not 0 or 1.
Dave Cross’s answer shows that you shouldn’t have to think about it. But, if there’s some reason you need to convert it to plain 1 or 0, there are some Perl idioms:
Here’s the output:
Note that the
!!
in the false case does not give back zero. Instead, it’s the empty string. I include that because you’ll see that idiom to double negate a value, although that’s more about turning a non-zero length string into 1 or the empty string.The conditional version is probably more appropriate if you need to select one of two special values (perhaps for a database column):