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

Hi, I'm new to JSON and I want to retrieve the value of a json response attribute here is m code
#!/usr/bin/perl use warnings; use Shell; use JSON; main(); sub get_balance { my $test = libra("account balance f270b16e2fec7a10937d0c32eec34a9b +2280a7ab8a64e75aa8c84e3583158349"); print "$test"; } sub main { get_balance(); }
it's print : root@vps8279:/usr/lib/cgi-bin# perl libra_test.pl { "balance": 999000000 } what I need is just the result : 999000000 thx

Replies are listed 'Best First'.
Re: format json response
by haukex (Archbishop) on Oct 29, 2019 at 13:48 UTC

    This should work:

    my $json = qq/{\n\t"balance": 999000000\n}\n/; my $data = decode_json($json); my $balance = $data->{balance}; print $balance, "\n"; # prints "999000000"

    The decode_json function is provided by many of the JSON modules, personally I prefer Cpanel::JSON::XS. You can use Data::Dumper or Data::Dump to inspect its return value, and then dereference it accordingly (perlreftut).

    use Shell;

    Note that Shell is fairly dangerous, as it'll turn any unknown function call into a system command. I assume libra is that shell command? You might be interested in my module IPC::Run3::Shell, which is heavily inspired by Shell, but I've added a bunch of features (and, relatively speaking, more safety from common problems).

    use IPC::Run3::Shell { chomp=>1 }, qw/ libra /; my $balance = libra(qw/ account balance f270b16e2fec7a10937d0c32eec34a +9b2280a7ab8a64e75aa8c84e3583158349 /);
Re: format json response
by 1nickt (Canon) on Oct 29, 2019 at 13:55 UTC

    Hi welcome to the Monastery. We just saw your buddy doing the Bitcoin app a few months ago! Nice to see y'all are keeping up with the new stuff ;-)

    I suggest to read the documentation for JSON as well as about Perl data structures (perldsc) so you can access hash elements at will.

    Also, I suggest getting handy with jq so you can parse random JSON on the commandline. For instance, you could extend your command shown to:

    # perl libra_test.pl | jq .balance

    Hope this helps!


    The way forward always starts with a minimal test.
      Well thank you so much :-)