6

The command

curl "https://tools.keycdn.com/geo.json?host={18.205.6.240}"

returns the following JSON document:

{"status":"success","description":"Data successfully received.","data":{"geo":{"host":"18.205.6.240","ip":"18.205.6.240","rdns":"ec2-18-205-6-240.compute-1.amazonaws.com","asn":14618,"isp":"AMAZON-AES","country_name":"United States","country_code":"US","region_name":"Virginia","region_code":"VA","city":"Ashburn","postal_code":"20149","continent_name":"North America","continent_code":"NA","latitude":39.0469,"longitude":-77.4903,"metro_code":511,"timezone":"America\/New_York","datetime":"2022-06-17 10:44:39"}}}

In this output, I need to extract the country_name. I am not sure how to do that.

0

2 Answers 2

14
$ curl -s 'https://tools.keycdn.com/geo.json?host={18.205.6.240}' | jq -r '.data.geo.country_name'
United States

The jq expression .data.geo.country_name extracts the given item in the JSON document returned from the endpoint that you access with curl.

0
2

If you can use the below version also: Below is REST API output:

{
  "error": "none",
  "message": "Success",
  "data": {
    "name": "Vishal Biradar",
    "userId": 1,
  }
}

Below is the script code that shows how we can read it.

#!/bin/bash
LOGIN_DATA=$(\
    curl -d "[email protected]&password=abcd123" \
    http://localhost:1234/login \
    | python -c "import sys, json; print json.load(sys.stdin)['data']['name']"\
)
echo "LOGIN_DATA=$LOGIN_DATA"
3
  • print(json.load(sys.stdin)['access_token']) in case of python 3+. Great solution anyway
    – José
    Jun 30, 2021 at 4:10
  • Apart from being about parsing out a specific part of some JSON document, this does not seem to be related to the problem at hand. You could have used the example document quoted in the question instead.
    – Kusalananda
    Aug 24, 2021 at 11:43
  • Might as well just use python in this case Jul 22, 2022 at 10:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .