在简单的perl或简单的unix中分解JSON字符串?

Tre*_*lph 3 c unix perl json objective-c

好的,所以我有这个

{"status":0,"id":"7aceb216d02ecdca7ceffadcadea8950-1","hypotheses":[{"utterance":"hello how are you","confidence":0.96311796}]}
Run Code Online (Sandbox Code Playgroud)

目前我正在使用此shell命令对其进行解码以获取我需要的字符串,

echo $x | grep -Po '"utterance":.*?[^\\]"' | sed -e s/://g -e s/utterance//g -e 's/"//g'
Run Code Online (Sandbox Code Playgroud)

但这只适用于你使用perl编译的grep以及我用来获取perl的JSON字符串的脚本,所以有什么方法可以在简单的perl脚本或简单的unix命令中进行相同的解码,或者更好,c或objective-c?

我用来获取json的脚本,http://pastebin.com/jBGzJbMk,如果你想使用一个文件,那么请下载http://trevorrudolph.com/a.flac

Eri*_*rom 6

怎么样:

perl -MJSON -nE 'say decode_json($_)->{hypotheses}[0]{utterance}'
Run Code Online (Sandbox Code Playgroud)

以脚本形式:

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


TLP*_*TLP 5

好吧,我不确定我是否可以正确推断出你的内容,但这是一种在perl中解码JSON字符串的方法.

当然,您需要知道数据结构才能获得所需的数据.打印"话语"字符串的行在下面的代码中注释掉.

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;
Run Code Online (Sandbox Code Playgroud)

输出:

$VAR1 = {
          'status' => 0,
          'hypotheses' => [
                            {
                              'utterance' => 'hello how are you',
                              'confidence' => '0.96311796'
                            }
                          ],
          'id' => '7aceb216d02ecdca7ceffadcadea8950-1'
        };
Run Code Online (Sandbox Code Playgroud)

快速破解:

while (<>) {
    say for /"utterance":"?(.*?)(?<!\\)"/;
}
Run Code Online (Sandbox Code Playgroud)

或者作为一个单行:

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

如果您碰巧使用Windows,那么单线程会很麻烦,因为它"是由shell解释的.

快速破解#2:

这将有希望通过任何哈希结构和查找键.

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;
}
Run Code Online (Sandbox Code Playgroud)