Reputation: 1
I have this:
{"First":"ID", "Second":"{\"@cond\": [true, false]}"}
I have written a code:
use strict;
use warnings;
use feature 'say';
use JSON;
use utf8;
my $data = do { local $/; <DATA> };
my $d = decode_json($data);
$d->{Second} = decode_json( $d->{Second} );
say extractt($d);
sub extractt{
my $inf = $d->{Second}{cond}[0]
return $inf
}
__DATA__
{"First":"ID", "Second":"{\"@cond\": [true, false]}"}
My desired output is 'true, false' as a string.
However, i get nothing. What im doing wrong? How to fix it?
Upvotes: 0
Views: 77
Reputation: 166
Used the script to generated the needed JSON for testing see the commented code.
Remember that perl does not use the words true
and false
as boolean indicators.
use strict;
use warnings;
use feature 'say';
use JSON;
use utf8;
# Used to generate the JSON data expected by the program
#my $data = {
# First => 'ID',
# Second => encode_json ({ cond => ['true', 'false'] })
#};
#
#say encode_json ($data);
# The original code with the JSON data updated
my $data = do { local $/; <DATA> };
my $d = decode_json($data);
$d->{Second} = from_json( $d->{Second} );
say 'rec1 '.extractt ($d, 0);
say 'rec2 '.extractt ($d, 1);
sub extractt{
my $data = shift;
my $index = shift;
my $inf = $data->{Second}{cond}[$index];
return $inf;
}
__DATA__
{"First":"ID","Second":"{\"cond\":[\"true\",\"false\"]}"}
If the JSON data need to be boolean true and false
{"First":"ID","Second":"{\"cond\":[true,false]}"}
the extractt method will see the values in perl as 1 and 0 so a small change will be needed to get the words returned:
my $inf = ($data->{Second}{cond}[$index])? 'true' : 'false';
Upvotes: 2