我有一个小 bash 程序,它调用返回 JSON 数据的 web 服务。
我自己编写了 web 服务程序,我可以完全控制它的数据源,因此我可以信任返回的数据。
现在我想对数据做点什么。
数据是一个没有嵌套的简单、简短的键值结构,如下所示:
{
"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",
}
现在我使用这个单行来反序列化返回到 perl 代码的 json 结构。请参阅此代码段的最后一行:
#!/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 $@ if $@; say $h{outfile_excel}')
例如,我不确定为什么要提出 %{$_} 构造。有一个更好的方法吗?写最后一行有更短或更安全的方法吗?
SE 编辑:如果你愿意,你可以把这篇文章移到 codereview stackexchange 网站上,但我在那里没有账户。
编辑:在 8 个月后重新访问该帖子后,我想补充一点,这些天我使用这个衬垫来获取我的 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' -