如何改进这个perl/bash单线程来反序列化json数据

问题描述:

我有一个bash程序调用一个返回JSON数据的webservice。如何改进这个perl/bash单线程来反序列化json数据

我自己编写了webservice程序,我完全控制了它的数据源,因此我可以信任返回的数据。

现在我想对数据做些什么。

的数据是没有嵌套一个简单的,短的键值结构,看起来像这样:

{ 
    "asciifile" : "../tmp/data_20120720_105746-01580.txt", 
    "excelfile" : "../tmp/data_01580-20120720_105746.xlsx", 
    "from" : "Jun 19, 2012", 
    "msg" : "some info message, for the admin", 
    "outfile" : "data--recent.txt", 
    "outfile_excel" : "data--recent.txt.xlsx", 
    "resolution" : "std" 
    "to" : "Jul 20, 2012", 
    "url_comment" : "another info message, for the screen/user", 
    "url_outfile" : "http://www.example.com/path/tmp_cached_files/data--recent.txt", 
    "url_outfile_excel" : "http://www.example.com/path/tmp_cached_files/data--recent.txt.xlsx", 

} 

现在我用这一个班轮反序列化JSON结构返回给Perl代码。看到这段代码的最后一行:

#!/bin/bash 
cmd=$(curl_or_wget_call_to_webservice) 
output=$(eval $cmd) 
outfile_excel=$(echo "$output"| json_xs -f json -t dumper | tee | perl -n0777 -E 'eval "%h=%{$_}"; warn [email protected] if [email protected]; say $h{outfile_excel}') 

例如,我不知道为什么我想出%{$ _}构造。 有没有更好的方法来做到这一点?有没有更简单的方法或更安全的方式来写最后一行?

SE编辑:如果您愿意,您可以将此帖子移至codereview stackexchange网站,但我没有账户。

编辑:6个月后重温文章后,我想补充一点,这几天我用这一个班轮为得到我的github回购的名字:

wget --quiet --auth-no-challenge --user knbknb --password secret -O - 
https://api.github.com/user/repos | 
perl -MJSON -n0777 -E '$r = decode_json($_); map {say $_->{name}} @$r' - 

jshon。你可以简单地打电话给像

curl http://somehere.tld/data.json | jshon -e url_outfile_excel 

这将打印给定的键的值。

顺便说一句。控制Web服务不会使输入值得信赖。致电eval时要小心。

Perl可以解码JSON本身,所以下一个应该给出一些想法,使用LWP :: Simple来获得一些json数据。

perl -MLWP::Simple -MJSON \ 
-e '$ref = decode_json(get("http://your.url/to/webservice")); print $ref->{outfile_excel}' 

的$裁判包含所有的JSON数据的Perl结构,打印出你想要的吧..