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

前端 未结 3 1106
有刺的猬
有刺的猬 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:32

    Here's my program:

    #! /usr/bin/env perl
    
    use strict;
    use warnings;
    use feature qw(say);
    
    use JSON;
    
    my @array;
    for my $number ( (1..5) ) {
        push @array, $number;
    }
    say to_json( {"number_array" => \@array} );
    

    And here's my result:

    {"number_array":[1,2,3,4,5]}
    

    That's what you want. Right?

    Let's change my push from push @array , $number; to push @array "$number"; where $number is in quotes as if it's a string:

    #! /usr/bin/env perl
    
    use strict;
    use warnings;
    use feature qw(say);
    
    use JSON;
    
    my @array;
    for my $number ( (1..5) ) {
        push @array, "$number";
    }
    say to_json( {"number_array" => \@array} );
    

    Now I get:

    {"number_array":["1","2","3","4","5"]}
    

    Somehow JSON was able to detect that these numbers were pushed in as strings. Let me loop again and add a zero to each element:

    #! /usr/bin/env perl
    
    use strict;
    use warnings;
    use feature qw(say);
    
    use JSON;
    
    my @array;
    for my $number ( (1..5) ) {
        push @array, "$number";
    }
    
    @array  = map { $_ += 0 } @array; #Add a 0 to each element
    
    say to_json( {"number_array" => \@array} );
    

    Back to:

    {"number_array":[1,2,3,4,5]}
    

    Looks like you have to add a zero to each element of your array to convert the string back to a numeric value.

提交回复
热议问题