Break down JSON string in simple perl or simple unix? Break down JSON string in simple perl or simple unix? unix unix

Break down JSON string in simple perl or simple unix?


How about:

perl -MJSON -nE 'say decode_json($_)->{hypotheses}[0]{utterance}'

in script form:

use JSON;while (<>) {   print decode_json($_)->{hypotheses}[0]{utterance}, "\n"}


Well, I'm not sure if I can deduce what you are after correctly, but this is a way to decode that JSON string in perl.

Of course, you'll need to know the data structure in order to get the data you need. The line that prints the "utterance" string is commented out in the code below.

use strict;use warnings;use Data::Dumper;use JSON;my $json = decode_json q#{"status":0,"id":"7aceb216d02ecdca7ceffadcadea8950-1","hypotheses":[{"utterance":"hello how are you","confidence":0.96311796}]}#;#print $json->{'hypotheses'}[0]{'utterance'};print Dumper $json;

Output:

$VAR1 = {          'status' => 0,          'hypotheses' => [                            {                              'utterance' => 'hello how are you',                              'confidence' => '0.96311796'                            }                          ],          'id' => '7aceb216d02ecdca7ceffadcadea8950-1'        };

Quick hack:

while (<>) {    say for /"utterance":"?(.*?)(?<!\\)"/;}

Or as a one-liner:

perl -lnwe 'print for /"utterance":"(.+?)(?<!\\)"/g' inputfile.txt

The one-liner is troublesome if you happen to be using Windows, since " is interpreted by the shell.

Quick hack#2:

This will hopefully go through any hash structure and find keys.

my $json = decode_json $str;say find_key($json, 'utterance');sub find_key {    my ($ref, $find) = @_;    if (ref $ref) {        if (ref $ref eq 'HASH' and defined $ref->{$find}) {            return $ref->{$find};        } else {            for (values $ref) {                my $found = find_key($_, $find);                if (defined $found) {                    return $found;                }            }        }    }    return;}


Based on the naming, it's possible to have multiple hypotheses. The prints the utterance of each hypothesis:

echo '{"status":0,"id":"7aceb216d02ecdca7ceffadcadea8950-1","hypotheses":[{"utterance":"hello how are you","confidence":0.96311796}]}' | \   perl -MJSON::XS -n000E'      say $_->{utterance}         for @{ JSON::XS->new->decode($_)->{hypotheses} }'

Or as a script:

use feature qw( say );use JSON::XS;my $json = '{"status":0,"id":"7aceb216d02ecdca7ceffadcadea8950-1","hypotheses":[{"utterance":"hello how are you","confidence":0.96311796}]}';say $_->{utterance}   for @{ JSON::XS->new->decode($json)->{hypotheses} };