Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Can I prevent JSON encode from converting values

by somekindafreak (Acolyte)
on Jul 20, 2012 at 18:48 UTC ( [id://982883]=perlquestion: print w/replies, xml ) Need Help??

somekindafreak has asked for the wisdom of the Perl Monks concerning the following question:

I am working with JSON data on a block of product versions. Therefore I want 5.0 to remain as a '5.0' string without being converted to an integer and without adding any token trailing characters. When I run:
my $json=JSON->new->allow_nonref; my $var='5.0'; print $json->encode( { $var => $var } );
the output is {"5.0" : 5}. I need {"5.0" : "5.0" } I've spent a ton of time searching the documentation and experimenting without finding a solution. There is a blurb on stringifying a value by wrapping it in quotes or adding a trailing ."" but neither do the trick. It also strips leading zeros while maintaining the float value, 5.10 becomes 5.1

Replies are listed 'Best First'.
Re: Can I prevent JSON encode from converting values
by Your Mother (Archbishop) on Jul 20, 2012 at 21:06 UTC

    Upgrade? And ensure you've got JSON::XS. I've got 2.22.

    perl -MJSON -le '$var = "5.0"; print JSON->new->allow_nonref->encode({ +$var => $var})' {"5.0":"5.0"}
      I have JSON::XS version 2.29. Perhaps I should downgrade? Actually I am developing for a static perl environment that I can't touch either way.

        I'm on 2.32 and get { "5.0": "5.0" }.

        perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re: Can I prevent JSON encode from converting values
by aitap (Curate) on Jul 20, 2012 at 19:01 UTC
    Does { $var => sprintf("%.01f",$var) } solve all possible cases?
    Sorry if my advice was wrong.
Re: Can I prevent JSON encode from converting values
by Anonymous Monk on Jul 20, 2012 at 19:46 UTC
    As far as I know the JSON format is basically "JavaScript" and as such it does not reliably know whether a string that could be a number, or a number that could be a string, are one fundamental type or another.

      JSON (and Javascript for that matter) distinguishes between integers and strings; it's Perl that does not.

      perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://982883]
Approved by MidLifeXis
Front-paged by MidLifeXis
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2024-04-25 19:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found