0

i have this print STDERR Dumper $data:
$VAR1 = '{
"url_date":null,
"footer":null,"id":"18",
"authors":[
{"initials":"B.","last_name":"Best","has":0,"id":12},
{"initials":"D.","last_name":"Dough","has":1,"id":10},
{"initials":"F.","last_name":"Fuss","has":0,"id":15,}
],
"url_headline":null,
"headline":"test"}';

i would like to to access Dough how would i do that?
i tried print STDERR Dumper $data.authors[1].last_name but got syntax error.

2nd try
use JSON::XS qw( decode_json );
my $coder = JSON::XS->new->utf8->pretty->allow_nonref;
my $p = $coder->decode ($.data);

2 Answers 2

4

You have a string. What the string contains is valid JSON and valid YAML. You need to parse the JSON, and the best way to do that is with an existing parser like JSON::XS.

use JSON::XS qw( decode_json );
my $data = decode_json($data_json);
$data->{authors}[1]{last_name}
Sign up to request clarification or add additional context in comments.

4 Comments

i have a syntax error... i updated the code see 2nd try. print STDERR Dumper %{$p}; gave me the whole $data info but when i do print STDERR Dumper %{$p}->authors[1]{last_name}; i have a syntax error too..
That's cause you didn't use what I posted.
i did tried what you posted and got syntax error at line 78, near "->authors[" then i when to the JSON::XS page and found the 2nd try and have a syntax error too.. what is the problem?
$p->{authors}[1]{last_name} not %{$p}->authors[1]{last_name}. Looks like you're trying to call a method on a what ends up being a string. %{$p} with stringify the hashref and then you're trying to call a method on that. You just need to dereference that hashref like $p->{account}.
2

The best way is to decode string to Perl hash reference first with JSON module and then use regular Perl's hash access syntax $data->{"authors"}[1]{"last_name"}.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.