Converting array of numbers to json in perl, getting array of strings

前端 未结 3 1069
有刺的猬
有刺的猬 2021-01-19 11:12

I\'m trying to convert an array of numbers to json:


   $json = to_json(\"numbers_array\" => \\@numbers_array);
   print $json;

but the output I\'m get

3条回答
  •  北海茫月
    2021-01-19 11:18

    In addition to earlier answers: it's not a question of the definition of your data but of usage.

    From the JSON::XS pod:

    JSON::XS will encode […] scalars that have last been used in a string context before encoding as JSON strings, and anything else as number value

    Consider this piece of code:

    use JSON::XS;
    my $numbers = [123,124,125];
    print "A number: $numbers->[1]\n";            #<- use 2nd entry in string context.
    print JSON::XS->new->encode ($numbers)."\n";
    

    It prints:

    A number: 124
    [123,"124",125]
    

    Would you have expected that number 124 be encoded as string? Beware!

    (I learned that the hard way chasing a heisenbug that only showed up when I had some debug logging active.)

提交回复
热议问题