Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Encountered object '5.03 ', but neither allow_blessed nor convert_blessed settings are enabled

by davido (Cardinal)
on Aug 13, 2015 at 16:55 UTC ( [id://1138453]=note: print w/replies, xml ) Need Help??


in reply to Encountered object '5.03 ', but neither allow_blessed nor convert_blessed settings are enabled

First, you'll just end up confusing yourself again if you call a variable used to hold a datastructure "$json". Also, printing to a file is just adding unnecessary complexity that makes it harder to test. Just print, and see the output. Here's a small script with those adaptations:

#!/usr/bin/env perl use strict; use warnings; use JSON::PP; my $data = { 'book' => { 'title' => JSON::PP::true, 'pages' => 5.03 #this number } }; my $json = encode_json($data); print $json, "\n"; __END__ {"book":{"pages":5.03,"title":true}}

The part after __END__ is the output I saw on my screen. It indicates that you are indeed getting 5.03, the number. Are you seeing different results? If so, it probably has to do with the heuristics that JSON::PP uses to decide if something is a number or a string. It might do some introspection to determine if the number has ever been used as a string. Examples of what can make Perl think internally that a scalar variable holds a string include obvious string operations such as concatenation, less obvious such as sprintf, and even the common case of using print.

Your actual code may be something like pages => $number, but you may at one point have treated $number as a string. And in so doing, Perl starts thinking the variable holds a string (this is an internal process... an implementation detail leaking out). You can force numification by using a numerical operator at a carefully chosen time:

my $data = { book => { title => JSON::PP::true, pages => 0+$number, } };

Now we're forcing numeric context on $number.


Dave

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2024-03-28 19:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found