How to check if JSON hash key contains in perl?

I send a request to the endpoint URL, from where I get a response if successful in the JSON form, but if it does not work, it returns a specific text.

Sending a request:

$data->{response} = $self->{_http}->send($myData); 

So, before doing this:

 $resp = from_json($data->{response}); 

I want to check if the response is in json format or not. How can we handle this with Perl's kind help in this

+5
source share
3 answers

You can catch the exception from_json() ,

 my $resp; my $ok = eval { $resp = from_json("{}"); 1 }; $ok or die "Not valid json"; 

or easier

 my $resp = eval { from_json("rrr") }; $resp // die "Not valid json"; 
+5
source

Use JSON or JSON :: XS to decode JSON in a Perl structure.

A simple example:

 use strict; use warnings; use JSON::XS; my $json = '[{"Year":"2012","Quarter":"Q3","DataType":"Other 3","Environment":"STEVE","Amount":125},{"Year":"2012","Quarter":"Q4","DataType":"Other 2","Environment":"MIKE","Amount":500}]'; my $arrayref = decode_json $json; foreach my $item( @$arrayref ) { # fields are in $item->{Year}, $item->{Quarter}, etc. } 
0
source

You can use the try / catch block using Try :: Tiny

 use Try::Tiny; try { $resp = from_json($data->{response}); } catch { # Do something if it does not parse warn 'Could not parse json' }; 
0
source

Source: https://habr.com/ru/post/1212172/


All Articles