Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Int becomes String when I convert to json

by choroba (Cardinal)
on May 09, 2022 at 19:28 UTC ( [id://11143715]=note: print w/replies, xml ) Need Help??


in reply to Int becomes String when I convert to json

That's why Cpanel::JSON::XS::Type exists.
#!/usr/bin/perl use warnings; use strict; use Cpanel::JSON::XS; use Cpanel::JSON::XS::Type; my %out = (username => "", userid => "", status => "", filename => "", rawfilename => "", ticket => "", returnvalue => 0, message => ""); my $json = encode_json(\%out, {returnvalue => JSON_TYPE_INT, username => JSON_TYPE_STRING, userid => JSON_TYPE_STRING, status => JSON_TYPE_STRING, filename => JSON_TYPE_STRING, rawfilename => JSON_TYPE_STRING, ticket => JSON_TYPE_STRING, message => JSON_TYPE_STRING}); print $json;

map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Replies are listed 'Best First'.
Re^2: Int becomes String when I convert to json
by bartender1382 (Beadle) on May 10, 2022 at 02:02 UTC

    I wonder if it's that a single digit it normally returns an int, but for a double digit a string.

    I'll try Cpanel::JSON::XS::Type, but sort of irks me that this is a "thing."

    Thank you
      > that a single digit it normally returns an int, but for a double digit a string.

      It's more complex than that. It depends on what you did with the value, on the version of Perl, what JSON module you use and its version, and sometimes even more. See my slides on the topic.

      map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

        You really do attack the problem. But since I didn't explicitly see it, and am a bad reader, I just want to be sure that implementing...

        use Cpanel::JSON::XS::Type; sub makeJSON { (my $hashref) = @_; my $json = encode_json($hashref, {returnvalue => JSON_TYPE_INT, username => JSON_TYPE_STRING, userid => JSON_TYPE_STRING, status => JSON_TYPE_STRING, filename => JSON_TYPE_STRING, rawfilename => JSON_TYPE_STRING, ticket => JSON_TYPE_STRING, message => JSON_TYPE_STRING}); return $json; }

        ...covers my bases.

        Although am still a little offset that sometimes it turned it into a string, and sometimes not. But I'll get over it.

        Again, thanks for making slides to let people know.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11143715]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (8)
As of 2024-04-23 17:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found