Home: Perl Programming Help: Beginner:
Parse JSON with PERL



robertico
Novice

Mar 21, 2013, 1:37 PM


Views: 2463
Parse JSON with PERL

I'd like to parse a JSON string with PERL.

My JSON string;


Code
{"to_id": 0, "message": "This is a sample", "message_id": 1000, "from_id": 999}


How to parse the JSON and return all objects and values.

Sample output;

Code
to_id                0 
message This is a sample
message_id 1000
from_id 999


I need the objects and values as separate variables. JSON strings are not all the same.

So I assume i need a loop to iterate all objects and values.

Thanks in advance


Zhris
Enthusiast

Mar 21, 2013, 1:57 PM


Views: 2460
Re: [robertico] Parse JSON with PERL

Hi,

Use JSON from CPAN:


Code
#!/usr/bin/perl 
use strict;
use warnings FATAL => qw/all/;
use JSON;
use Data::Dumper;

my $json_string = '{"to_id": 0, "message": "This is a sample", "message_id": 1000, "from_id": 999}';

my $json_object = JSON->new( );

my $perl_ref = $json_object->decode( $json_string );

print Dumper( $perl_ref );


Output:

Code
$VAR1 =  
{
'from_id' => 999,
'message_id' => 1000,
'to_id' => 0,
'message' => 'This is a sample'
};


Chris


(This post was edited by Zhris on Mar 21, 2013, 1:59 PM)


robertico
Novice

Mar 21, 2013, 10:00 PM


Views: 2448
Re: [Zhris] Parse JSON with PERL

Hi Chris

I'm stuck with this part;


Code
$VAR1 =  
{
'from_id' => 999,
'message_id' => 1000,
'to_id' => 0,
'message' => 'This is a sample'
};


I'm new to PERL and I can't find a solution to extract the 'key' and the 'value' in separate parts (variables) from $VAR1.

Were can I find more information about this or can you give me a hint?

Robertico


(This post was edited by robertico on Mar 21, 2013, 10:14 PM)


Zhris
Enthusiast

Mar 22, 2013, 2:21 AM


Views: 2441
Re: [robertico] Parse JSON with PERL

Hi Robertico,

What you are seeing in "output" is Data::Dumper stringifying the data structure for easier reading.

In your case you are dealing with a simple one level hash reference ($perl_ref).

You can loop through it:

Code
while ( my ( $key, $value ) = each ( %$perl_ref ) ) 
{
print "$key, $value\n";
}


Or access each value directly by its key:

Code
print $perl_ref->{from_id} . "\n"; 
print $perl_ref->{message_id} . "\n";
print $perl_ref->{to_id} . "\n";
print $perl_ref->{message} . "\n";


etc...

For more complex data structures, particular those that may vary in levels with unknown keys, you could use a recursive processing routine.

Chris


(This post was edited by Zhris on Mar 22, 2013, 2:23 AM)


robertico
Novice

Mar 22, 2013, 2:37 AM


Views: 2438
Re: [Zhris] Parse JSON with PERL

Thank you very much (also for the explanation). Works excellent.
I can continue Wink