Parsing JSON response in Python3

Viewed 698

My code is:

self.ip = self.bot.get('https://icanhazip.com').content.rstrip().decode()

I want to replace https://icanhazip.com with https://ipinfo.io, but I don't know how to extract the ip returned:

$ curl "ipinfo.io"
{
  "ip": "xx.xx.xx.xx",
  "city": "",
  "region": "",
  "country": "xx",
  "loc": "xx.xxx.xx.xxx",
  "org": "xxxxxxx Communication Company (Private Joint Stock)"
}
1 Answers

It's not clear which HTTP library you're using in self.bot.get, but for a generic one (where content returns a string), you can parse the JSON response manually with json.loads:

import json
# ...
ip = json.loads(self.bot.get('https://ipinfo.io').content).get('ip')

If you're using requests, you can read the JSON response directly with json() method on the response:

ip = self.bot.get('https://ipinfo.io').json().get('ip')
Related