Chetan
Chetan

Reputation: 1281

How to convert a string to hash in perl without using regex or split

I have a function i cannot control which returns a string which is acutally a hash. It looks something like below:

{"offset":0,"limit":500,"count":0,"virtual_machines":[]}

I need to check if the count is greater than 0. Because the output is a string and not a hash, i am trying to split the string and get the output from it.

The snippet for the same is below:

my $output = '{"offset":0,"limit":500,"count":0,"virtual_machines":[]}';
$output =~ s/ +/ /g;
my @words = split /[:,"\s\/]+/, $output;
print Dumper(@words);

The output for this is:

$VAR1 = '{';
$VAR2 = 'offset';
$VAR3 = '0';
$VAR4 = 'limit';
$VAR5 = '500';
$VAR6 = 'count';
$VAR7 = '0';
$VAR8 = 'virtual_machines';
$VAR9 = '[]}';

Now, i can get the value $VAR7 and get the count.

Is there a way to convert a string to hash and then use the keys to get the values instead of using regex and split. Can someone help me out here!

Upvotes: 0

Views: 484

Answers (2)

davernator
davernator

Reputation: 230

If all colons are just separators, then you can replace them with '=>'s and eval the string. That's probably unrealistic, though. So you can use JSON ... looks like the string is in JSON format. Try the following (worked for me :-):

#!/usr/bin/perl

use JSON::Parse 'parse_json';

# the string is JSON
my $jstr = '{"offset":0,"limit":500,"count":0,"virtual_machines":[]}';

# oversimplified (not using json ... o.k. if no colons anywhere but as separators
my $sstr = $jstr;
$sstr =~ s/:/=>/g;
my $href = eval "$sstr";
printf("From oversimplified eval, limit == %d\n", $href->{limit});

# using JSON (looks like string is in JSON format).
# get JSON::Parse from CPAN (sudo cpan JSON::Parse)
my $jref = parse_json($jstr);
printf("From JSON::Parse, limit == %d\n", $jref->{limit});

1;


Output:

From oversimplified eval, limit == 500
From JSON::Parse, limit == 500

Upvotes: -3

melpomene
melpomene

Reputation: 85767

That string is in JSON format. I'd simply do

use strict;
use warnings;
use JSON::PP qw(decode_json);

my $output = '{"offset":0,"limit":500,"count":0,"virtual_machines":[]}';
my $data = decode_json $output;

print $data->{count}, "\n";

Upvotes: 5

Related Questions