How to improve this perl / bash single line for json data deserialization

I have a small bash program that calls a web service that returns JSON data.

I wrote the webservice program myself, I have full control over its data sources, and therefore I can trust the returned data.

Now I want to do something with the data.

The data is a simple short key-value structure without nesting and looks like this:

{ "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", } 

Now I use this single-line layer to deserialize the json structure returned in perl code. See the last line of this snippet:

 #!/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}') 

For example, I'm not sure why I came up with the% {$ _} construct. Is there a better way to do this? Is there a shorter way or a safer way to write the last line?

SE editors: if you want, you can transfer this message to the codexview stackexchange website, but I don't have an account there.

Edit: after reissuing the post after 8 months , I would like to add that these days I use this one liner to get the name of my github repository:

  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
source share
2 answers

There is jshon . You could just call something like

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

To print the value for this key.

By the way. Control over the web service does not make login reliable. Be careful when calling eval .

+3
source

Perl can decode JSON itself, so the next one should give some idea using LWP :: Simple to get some json data.

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

$ ref contains the perl structure of all JSON data, print as you want.

+5
source

All Articles