perlbashcode-snippets

how to improve this perl/bash one-liner to deserialize json data


I have a little bash program that calls a webservice that returns JSON data.

I have written the webservice program myself, I have complete control over its data sources, and thus I can trust the data that is returned.

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 am using this one-liner to deserialize the json structure returned to perl code. See 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 wish, you may move this post to the codereview stackexchange site, but I don't have an account there.

Edit: After revisiting the post after 8 months, I'd like to add that these days I use this one liner for getting the name of my github repos:

 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' -

Solution

  • There is jshon. You could simply call something like

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

    Which would print the value for the given key.

    By the way. Having control over the webservice doesn't make the input trustworthy. Be careful when calling eval.