Answer the question
In order to leave comments, you need to log in
How to parse JSON in Perl?
Hello everyone,
I have difficulty parsing data presented in JSON.
#!/usr/bin/perl
use diagnostics;
use JSON::XS;
use Data::Dumper;
my $json_data='{
"href" : "http://localhost/profiles",
"items" : [
{
"href" : "http://localhost/id111",
"Child" : {
"name" : "Jack",
"age" : "11",
"pet" : "Cat"
}
},
{
"href" : "http://localhost/id303",
"Child" : {
"name" : "David",
"age" : "8",
"pet" : "Dog"
}
},
{
"href" : "http://localhost/id516",
"Child" : {
"name" : "Merry",
"age" : "10",
"pet" : "Hamster"
}
}
]
}';
print Dumper(decode_json ($json_data));
$VAR1 = {
'href' => 'http://localhost/profiles',
'items' => [
{
'href' => 'http://localhost/id111',
'Child' => {
'pet' => 'Cat',
'name' => 'Jack',
'age' => '11'
}
},
{
'href' => 'http://localhost/id303',
'Child' => {
'age' => '8',
'name' => 'David',
'pet' => 'Dog'
}
},
{
'href' => 'http://localhost/id516',
'Child' => {
'name' => 'Merry',
'pet' => 'Hamster',
'age' => '10'
}
}
]
};
Answer the question
In order to leave comments, you need to log in
print Dumper( decode_json($json_data) );
my $ref = decode_json($json_data);
my $arr = $ref->{"items"};
for my $item ( @$arr ){
print $item->{"Child"}->{"name"}, " ", $item->{"Child"}->{"pet"};
print "\n";
}
Jack Cat
David Dog
Merry Hamster
This thing is called an "associative array", in Perl it's called a hash.
Values can be accessed via {}, for example VAR1{"items"}; will return you an array of items.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question