Open Source For You — December 2017

(Steven Felgate) #1

Developers How To


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

The JSON structure for this endpoint looks like what’s
shown in Figure 3.
Consolidated_weather contains an array of JSON objects
with weather information, and the sources key contains
an array of JSON objects from which particular weather
information was fetched.
This time, let’s store JSON in a file named weather.
json instead of directly piping data. This will help us

The output looks good, but what if we format the output
and print it on a single line? For that we can use string
interpolation. To use keys inside a string pattern, we use
backslash and parentheses so that they are not executed.

curl -sS https://www.metaweather.com/api/location/
search/\?query\=new | jq ‘.[] | “For \(.title) code is \
(.woeid)”’

“For New York code is 2459115”
“For New Delhi code is 28743736”
“For New Orleans code is 2458833”
“For Newcastle code is 30079”
“For Newark code is 2459269”

In our case, JSON is small, but if it is too big and we need
to filter it based on a key value (like display the information
for New Delhi), jq provides the select keyword for that
operation.

curl -sS https://www.metaweather.com/api/location/
search/\?query\=new | jq ‘ .[] | select(.title == “New
Delhi”) ‘

{
“title”: “New Delhi”,
“location_type”: “City”,
“woeid”: 28743736,
“latt_long”: “28.643999,77.091003”
}

Now that we have the Where on Earth ID (woeid) for
New Delhi, we can retrieve more information about New
Delhi using the endpoint https://www.metaweather.com/api/
location/woeid/.

Figure 2: Basic filters

Figure 3: JSON structure
Free download pdf