Perl - Pass JSON data to variable and compare with IF

Asked

Viewed 198 times

0

Good morning,

I have a request that I make in an API using GET (LWP::Useragent), the data is returned in a JSON, in JSON are returned up to two results at most as follows :

{"status":1,"time":1507891855,"response":{"prices":{"nome1\u2122":
{"preco1":1111,"preco2":1585,"preco3":1099},"nome2":
{"preco1":519,"preco2":731,"preco3":491}}}}

Dump :

$VAR1 = {
      'status' => 1,
      'time' => 1507891855,
      'response' => {
                      'prices' => {
                                    'nome1' => {
                                                 'preco1' => 1111,
                                                 'preco3' => 1099,
                                                 'preco2' => 1585
                                               },
                                    'nome2' => {
                                                 'preco3' => 491,
                                                 'preco1' => 519,
                                                 'preco2' => 731
                                               }
                                  }
                    }
    };

What I’d like to do is :

Take this data and save in a variable to make a comparison using IF with another variable that already has the name stored, the comparison would be with the name1/Nome2 and if it is true with the other variable it would take the preco2 and preco3 to print everything.

My biggest problem in this case is that some of these names in JSON contain characters like (Trademark) that comes as u2122 ( some cases are other characters ), so I can’t compare with the name of the other variable that is already with the correct name

nome1™

If I could just save the already "converted" JSON the characters would help me to manage with the rest.

Basically after making the request for the API I want to save the content in a variable already converting all u2122 to its respective character ( this is the part I don’t know how to do in Perl ) and then using another variable compare if the names are equal to show the price.

Thank you in advance for the help and any doubt please tell me that I try to explain again in another way.

1 answer

0


Problem solved using the following function:

use utf8;
use JSON::XS;

my $name = "nome1™";
my $var1 = decode_json $utf8_encoded_json_text;

# Compare with name in $name
if( defined $var1->{'response'}->{'prices'}->{$name} ) {
# Do something with the name that matches
my $match = $var1->{'response'}->{'prices'}->{$name};

print $match->{'preco1'}, "\n";
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.