JSON is more strongly typed than Perl. Perl (the language) is designed to not really make a strong distinction between an integer and a string. But internally there is a distinction. The "SV" entity that comprises a Perl scalar variable may have an "IV" (integer value) stored in it, or a "PV" (pointer to a string), or both (as well as a few other things). Perl mostly silently vivifies PV's and IV's within scalars as needed. So if you start with $var = 100;, that scalar variable holds just an IV. Now if you say print "$var\n";, $var goes through a stringification process that results in a PV being created within the scalar too. This is all taking place hidden behind the black box of Perl's internals, and in most circumstances this implementation detail is not relevant or even noticed.

However, JSON is typed, and JSON encoders have to decide whether a scalar contains an integer or a string. Most of the time the way they decide is by looking inside the variable to see if there is a PV. Remember, scalars may contain both. But the existence of an IV is overruled by the existence of a PV.

So you have to be very careful that this variable you're encoding has never been treated as a string. Or that a new variable is used: my $new_var = 0 + $var;.


Dave


In reply to Re: String to Integer, for json file by davido
in thread String to Integer, for json file by halecommarachel

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.