Cpanel-JSON-XS icon indicating copy to clipboard operation
Cpanel-JSON-XS copied to clipboard

inconsistent docs: handling of encoding `!0` and `!1`

Open karenetheridge opened this issue 4 years ago • 4 comments

The documentation says:

       Cpanel::JSON::XS::true, Cpanel::JSON::XS::false
           These special values become JSON true and JSON false values, respectively. You can also use "\1" and "\0" or "!0" and "!1" directly if you want.

..but !0 and !1 are not treated as booleans:

$; perl -MCpanel::JSON::XS -wle'print encode_json({ foo => !0 })'
{"foo":1}

$; perl -MCpanel::JSON::XS -wle'print encode_json({ foo => !1 })'
{"foo":""}

I'm not sure if it would be better to fix/add this behaviour, or simply not document any special treatment of !0 and !1. There is a SvTRUE macro in XS, but no SvFALSE. There is also PL_sv_yes and PL_sv_no.

karenetheridge avatar Jul 15 '21 19:07 karenetheridge

I'd like to offer a vote for changing the behaviour, rather than the documentation here.

On this point JSON::PP now behaves differently to both the Cpanel::JSON::XS and JSON::XS libraries. Its documentation says:

On perl 5.36 and above, will also return true when given one of perl's standard boolean values, such as the result of a comparison.

They settled on the new behaviour in version 4.11 (changelog), as documented in their pull-request 73 including their reason for not making it optional.

So JSON::PP allows me to write code like this: $data={is_adult=>!! ($age>17)} which seems better than what I currently do with the XS libraries: $data={is_adult=>$age>17 ? \1:\0}

I'm in the habit of using 0+$age to force a number, "".$phone to force a string and ?\1:\0 to force a boolean. !! is better because it's less typing and I can put it on the left of an expression as I do with numbers and strings.

$ perl -MJSON::PP -wlE'say $JSON::PP::VERSION; say encode_json({ foo => !1 })'
4.07
{"foo":""}
$ perl -MJSON::PP -wlE'say $JSON::PP::VERSION; say encode_json({ foo => !1 })'
4.16
{"foo":false}

rohanc avatar Mar 13 '23 02:03 rohanc

Yeah, see #214 We should stay compat to JSON::PP. And we had this behavior also, until people complained. A bit busy this week, on the weekend hopefully

rurban avatar Mar 14 '23 06:03 rurban

OK, thanks for your work on this important piece of infrastructure, over so many years.

Is there a github issue where the complaints were lodged? I was the one who submitted #214. Hope I didn't miss anything.

rohanc avatar Mar 14 '23 07:03 rohanc

Oops, forgot this for 4.38. Sorry

rurban avatar May 28 '24 07:05 rurban