sanjeevbinf has asked for the wisdom of the Perl Monks concerning the following question:

dear forum members,

my query must be a silly, but I have been finding hard to undestand json. Apart from knowing it is a key value pair, I cannot undertand much. How to initiate it. How to loop over it. How to print it without using print Dumper. Is it a hash or is it reference?

example:
my $son = '{ }'; my $r=decode_json($son);#cannot understand why I need to do $r->{"trans2"}[0]="90"; $r->{"trans2"}[1]="20"; print "\n\n"; #print Dumper \$r; # without dumper, how can I iterate using for loop? print $r->{"trans2"}[0],"\n"; #hard coded print $r->{"trans2"}[1],"\n"; #hard coded
Above, I want 2 values in trans1 key.

How do I iterate over keys in json object?

Sorry, I have posted this in wrong forum. Admins, pleae move this thread to respective forum

Replies are listed 'Best First'.
Re: understanding json in perl
by atcroft (Abbot) on Apr 25, 2014 at 04:43 UTC

    Looking at your code, first of all you only need the decode_json() statement if you have a value provided to you in JSON format. If not, then you can start with a familiar perl data structure, and use the encode_json() statement to convert it to something to be passed elsewhere. Here is a short example:

    Hope that helps.

      @atcroft Thank you for you the code. I needed the output like the encode one. Now I get the hold of it. Shall work on it.

      @ NetWallah , sundialsvc4- Thank you for the replies.

Re: understanding json in perl
by NetWallah (Canon) on Apr 25, 2014 at 05:35 UTC
    use strict; use warnings; use Data::Dumper; use JSON; my $son = '{ "trans2": [ 90, 20 , 80, 33 ] }'; # THIS IS a *STRING* my $r=decode_json($son);#cannot understand why I need to do # the 'decode' converts the string into a a perl structure (Hash re +f), and store in $r print Dumper \$r; # without dumper, how can I iterate using for loop? # Here's how to iterate .. for my $k (sort keys %$r){ print "Values under $k:\n"; for my $val (@{$r->{$k}}){ print "$val, "; } print "\n"; }
    Output:
    $VAR1 = \{ 'trans2' => [ 90, 20, 80, 33 ] }; Values under trans2: 90, 20, 80, 33,

            What is the sound of Perl? Is it not the sound of a wall that people have stopped banging their heads against?
                  -Larry Wall, 1992

Re: understanding json in perl
by locked_user sundialsvc4 (Abbot) on Apr 27, 2014 at 00:29 UTC

    JSON is, of course, merely a data-format.   In much younger and more innocent days, it was favored because it basically is JavaScript, and sites could (and did!) merely exec it.   Today, you use a CPAN module such as JSON (as previously shown) both to encode and to decode the data.   (Safely.)   What you get is a Perl data structure, namely a hash.