0

I am very new to JSON. I ran some commands and stored its output in string. Now i want to convert it into JSON. How can i convert it into perl hash referencces and then convert i into JSON. My output is like this but this is in string format :-

{"limits": {"rate": [], "absolute": {"maxServerMeta": 128, "maxPersonality": 5, "maxImageMeta": 128, "maxPersonalitySize": 10240, "maxSecurityGroupRules": 20, "maxTotalKeypairs": 100, "totalRAMUsed": 6144, "totalInstancesUsed": 3, "maxSecurityGroups": 10, "totalFloatingIpsUsed": 0, "maxTotalCores": 20, "totalSecurityGroupsUsed": 0, "maxTotalFloatingIps": 10, "maxTotalInstances": 10, "totalCoresUsed": 6, "maxTotalRAMSize": 51200}}}

I am using this code:-

my %hash_ref = split /[,:]/, $curl_cmd3_output;
   my $h = from_json( $hash_ref ); #<-- $h is a perl hash reference
  print $h;
  $max= $h->{'limits'}{'absolute'}{'maxSecurityGroupRules'}, "\n"; #<-- 20
print $max;

But i am getting this error

hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this) 

How to solve it ?

3
  • What do you mean that you're trying to convert your string to JSON? Commented Aug 13, 2014 at 6:41
  • @Miller as from the below solutions, i first need to convert my string into perl hash. then fetch values. Commented Aug 13, 2014 at 6:46
  • Okay ... your question is phrased poorly, because your string is already JSON. Nevertheless, if one of the below solutions answers your question, feel free to give them the check mark. Commented Aug 13, 2014 at 6:48

1 Answer 1

1

Your $curl_cmd3_output is a string representation of a JSON hash. First, you have to transform to a perl hash, and then read the key you are looking for:

use strict;
use warnings;
use JSON;

my $curl_cmd3_output = q!{"limits": {"rate": [], "absolute": {"maxServerMeta": 128, "maxPersonality": 5, "maxImageMeta": 128, "maxPersonalitySize": 10240, "maxSecurityGroupRules": 20, "maxTotalKeypairs": 100, "totalRAMUsed": 6144, "totalInstancesUsed": 3, "maxSecurityGroups": 10, "totalFloatingIpsUsed": 0, "maxTotalCores": 20, "totalSecurityGroupsUsed": 0, "maxTotalFloatingIps": 10, "maxTotalInstances": 10, "totalCoresUsed": 6, "maxTotalRAMSize": 51200}}}!;

my $h = from_json($curl_cmd3_output ); #<-- $h is a perl hash reference
print $h->{limits}->{absolute}->{maxSecurityGroupRules}, "\n"; #<-- 20
Sign up to request clarification or add additional context in comments.

1 Comment

i $curl_cmd3_output is the output of a command. So i cant hard code it as you did. I have to either pass a string or either run a command in q!{}!; Please tell me how to pass a string in this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.