Open Source For You — December 2017

(Steven Felgate) #1
How To Developers

http://www.OpenSourceForU.com | OPEN SOURCE FOR YOU | DECEMBER 2017 | 69

avoid making an API call every time we want to perform an
operation and, instead, we can use the saved JSON.


curl -sS https://www.metaweather.com/api/location/28743736/ >
weather.json


Now we can use jq in the format jq ‘filters’ weather.json
and we can also load filters from a file using the -f parameter.
The command is jq -f filters.txt weather.json, but we can just
load the JSON file and pass filters in the command line.
Let’s list the weather followed by the source name. Since
both sources and consolidated_weather is of the same length
(get the length using the length filter), we can use range
to generate an index and use string interpolation. There is
transpose and map inbuilt as well. Covering all of them won’t
be possible in a single article.


jq ‘range(0;([.sources[]] | length)) as $i | “ (.sources[$i]
.title) predicts (.consolidated_weather[$i] .weatherstate
name)”’ weather.json


“ BBC predicts Light Cloud”
“ Forecast.io predicts Clear”
“ Met Office predicts Clear”
“ OpenWeatherMap predicts Clear”
“ World Weather Online predicts Clear”
“ Yahoo predicts Clear”


There are so many functions and filters but we will use
sort_by and date functions, and end this article by printing the
forecast for each day in ascending order.


Format Date


This function takes value via the Pipe (|) operator


def format_date(x):
x |strptime(“%Y-%m-%d”) | mktime | strftime(“%a - %d,
%B”);


def print_location:


. | “
Location: (.title)
Coordinates : (.latt_long) “;


def print_data:


. | “


| (format_date(.applicable_date))\t\t |
| Humidity : .(.humidity)\t\t |
| Weather State: (.weather_state_name)\t\t\t |
------------------------------------------------”;


def process_weather_data:


. | sort_by(.applicable_date)[] | print_data;


Figure 4: Final output

By: Jatin Dhankhar
The author loves working with modern C++, Ruby, JavaScript
and Haskell. He can be reached at [email protected].

. as $root | print_location, (.consolidated_weather |
process_weather_data)


Save the above code as filter.txt.
sort_by sorts the value by data. format_date takes dates as
parameters and extracts short day names, dates and months.
print_location and print_data do not take any parameter,
and can be applied after the pipe operator; and the default
parameter for a parameterless function will be ‘.’

jq -f filter.txt weather.json -r

-r will return a raw string. The output is shown in Figure 4.
I hope this article has given you an overview of all that jq
can achieve. If you are looking for a tool that is easy to use in
shell scripts, jq can help you out; so give it a try.

[1] https://stedolan.github.io/jq/manual/v1.5/
[2] https://github.com/jatindhankhar/jq-tutorial
[3] https://www.metaweather.com/api/
[4] https://jqplay.org/

References
Free download pdf