Using jq with the OpenCage Geocoding API JSON response
jq
is a powerful command-line tool for manipulating JSON data.
However the syntax for using
jq
effectively can be a bit cryptic, and requires knowing the structure of
the JSON being parsed.
To save you time in this tutorial we lay out some examples of common
use cases around parsing the JSON format of our geocoding API results.
Please note:
jq
works on local JSON data, it does not fetch the data
from our API. You can do that with a command-line tool like
curl
,
wget
,
or similar, or have a script (in whichever programming language)
that calls the API and stores the
JSON response data in a file. Either way you then pipe the data to
jq
.
For readability in our examples below we will assume the data has been
fetched already (by whatever means) and stored as the file
api_response.json
Examples:
Print the
formatted
value of the first result
Display the
formatted
value of the first (0th) entry in the
results
array.
cat api_response.json | jq '.results[0].formatted'
Print the
formatted
value of all results
Display the
formatted
value of each entry in the
results
list.
cat api_response.json | jq '.results[].formatted'
Print multiple
components
values
Display the
country_code
and
country
values within the
components
portion of the first result
cat api_response.json | jq '.results[0].components | .country, .country_code'