Open Source For You — December 2017

(Steven Felgate) #1
How To Developers

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

Figure 1: Output comparison


:”28.643999,77.091003”},{“title”:”New Orleans”,”location_ty
pe”:”City”,”woeid”:2458833,”latt_long”:”29.953690,-
90.077713”},{“title”:”Newcastle”,”location_type”:”City”,
”woeid”:30079,”latt_long”:”54.977940,-1.611620”},{“title
”:”Newark”,”locationtype”:”City”,”woeid”:2459269,”latt
long”:”40.731972,-74.174179”}]


Let’s pretty format by piping the curl output to jq as follows:

curl -sS https://www.metaweather.com/api/location/
search/\?query\=new | jq


The screenshot shown in Figure 1 compares the output of
both commands.
Now that we have some data to work upon, we can use
jq to filter the keys. The simplest filter available is ‘.’ which
does nothing and filters the whole document as it is. Filters
are passed to jq in single quotes. By looking at the output, we
can see that all the objects are trapped inside a JSON array.
To filter out the array, we use .[] , which will display all items
inside an array. To target a specific item by index, we place
the index number inside .[0].
To display the first item, use the following code:


curl -sS https://www.metaweather.com/api/location/
search/\?query\=new | jq ‘.[0]’


{
“title”: “New York”,
“location_type”: “City”,
“woeid”: 2459115,
“latt_long”: “40.71455,-74.007118”
}


To display only the available cities, we add another filter,
which is the key name itself (in our case, .title). We can
combine multiple filters using the | (pipe) operator.
Here we combine the .[] filter with .title in this way: .[] |
.title. For simple queries, we can avoid the | operator and rewrite
it as .[] .title, but we will use the | operator to combine queries.

curl -sS https://www.metaweather.com/api/location/
search/\?query\=new | jq ‘.[] | .title’

“New York”
“New Delhi”
“New Orleans”
“Newcastle”
“Newark”

But what if we want to display multiple keys together?
Just separate them by ‘,’.
Now, let’s display the city along with its ID (woeid):

curl -sS https://www.metaweather.com/api/location/
search/\?query\=new | jq ‘.[] | .title,.woeid’

“New York”
2459115
“New Delhi”
28743736
“New Orleans”
2458833
“Newcastle”
30079
“Newark”
2459269
Free download pdf