4

我有一个小 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' -
4

2 回答 2

5

Perl 可以自己解码 JSON,所以接下来应该给出一些思路,使用 LWP::Simple 来获取一些 json 数据。

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

$ref 包含所有 JSON 数据的 perl 结构,根据需要打印出来。

于 2012-07-20T14:07:11.227 回答
3

jshon。你可以简单地调用类似的东西

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

这将打印给定键的值。

顺便一提。控制 web 服务并不能使输入可信。打电话时要小心eval

于 2012-07-20T11:58:03.780 回答