JSON does not return utf-8

Asked

Viewed 3,149 times

2

I am using freegeoip to know my location and use it in my program, but when I make a call using:

r = requests.get(location_url, headers={"content-type":"application/json;charset=UTF-8"})

The return stays like this:

{
  ip: "0.0.0.0",
  country_code: "BR",
  country_name: "Brazil",
  region_code: "SP",
  region_name: "Sao Paulo",
  city: "São Paulo",
  zip_code: "",
  time_zone: "America/Sao_Paulo",
  latitude: -20.1323,
  longitude: -50.6417,
  metro_code: 0
}

When I read using r.text, i need the accents in the words. How can I do this?

3 answers

2


Try to decode the answer manually:

r = requests.get(location_url)
texto = r.content.decode('utf8')

Note: r.json() may also be useful in your case.

  • Thank you so much, this way it worked. I was already hours trying to give Code in the text when I could give straight to content

0

Instead of using UTF-8 try to use ISO-8859-1:

r = requests.get(location_url, headers={"content-type":"application/json;charset=ISO-8859-1"})
  • Continues the same return.

  • How you are saving your file in your text editor?

  • I’m actually printing on a screen but I’m doing location = json.loads(r.text)

0

Instead of UTF-8 tries to use the latin1. I don’t know why, but I had the same problem and solved it like this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.