Search code examples
jsonperldouble-quotes

Pass variable with double quotes to JSON for REST client in PERL


Situation is the I am dealing with REST and JSON. Making JSON request for a REST client. I have a simple for loop that creates ids for me

for (my $i=1;$i<=2504;$i++)
 {
   push (@elements,$i);
 }
 my $ids = join ',',map{"\"$_\""}@elements;

However, when I pass this to JSON then I see backslash are being printed

$hashref=({"varreq"=>{"search"=>{"Ids"=>[$ids],"genome"=>[{"hugo"=>["$hugo"]}]},"output_format">{"groupby"=>"gene"}}});

Above is encoded in JSON and then a post request is made

I am getting this:

  "\"1\",\"2\",\"3\",\"4\",......

and I want:

  "1","2","3","4",.....

Solution

  • If you're doing JSON, why not just:

    use JSON;
    

    Rather than hacking it with regular expressions:

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    
    use JSON;
    
    my $json_str = to_json ( [1..2504] );
    print $json_str;
    

    With to_json you can encode into a JSON structure pretty much any perl data structure. (and from_json to turn it back again).

    You can do an OO style with encode_json/decode_json.

    You seem to be doing this already, but ... this here:

    {"Ids"=>[$ids],    
    

    Can be simply changed as the above:

    { "Ids" => [@elements]
    

    Which should do what you want.

    From the comments - I don't think anything receiving JSON should be getting confused by an array of numbers vs. an array of numeric strings.

    But if they do:

    my $json_str = to_json [ map {"$_"} 1..2504 ];