How to fix the Requests encoding in Python?

1

I'm studying Requests in Python and I'm trying to get the data from the zip code: link

p>

I can get it, but when it comes to showing them, since I live in São Paulo because of the encoding I get: S\u00e3o Paulo

Reading the requests tab ( link ) I know that it's possible to fix this using r.encoding, but I'm not getting it. What am I doing wrong?

import requests

CEP = 'http://api.postmon.com.br/v1/cep/'+ '01001001'   

r = requests.get(CEP)

r.encoding = 'ISO-8859-1'

print r.text

Result:

  

{"complement": "par side", "neighborhood": "S", "city": "S \ u00e9   Paulo "," public place ":" Praça da da à "," estado_info ":   {"area_km2": "248.221.996", "codigo_ibge": "35", "name": "S \ u00e3o"   Paulo "}," cep ":" 01001001 "," cidade_info ": {" area_km2 ":" 1521,11 ",   "code": "3550308"}, "status": "SP"}

    
asked by anonymous 17.04.2017 / 02:15

2 answers

3

This \u is an "escape" used in JSON and JavaScript for non-ASCII characters (by default Json uses Unicode), in case you returned as string, then it keeps using this to avoid loss of characters. p>

To get the accents just do the "parse" ( link ) of the data:

import json
import requests

CEP = 'http://api.postmon.com.br/v1/cep/'+ '01001001'

r = requests.get(CEP)

jsonparsed = json.loads(r.text)

print 'logradouro: ' + jsonparsed['logradouro']
print 'complemento: ' + jsonparsed['complemento']
print 'cep: ' + jsonparsed['cep']
print 'bairro: ' + jsonparsed['bairro']

print 'cidade: ' + jsonparsed['cidade']
print 'cidade info:'
print '+--- area_km2: ' + jsonparsed['cidade_info']['area_km2']
print '+--- codigo_ibge: ' + jsonparsed['cidade_info']['codigo_ibge']

print 'estado: ' + jsonparsed['estado']
print 'estado info:'
print '+--- area_km2: ' + jsonparsed['cidade_info']['area_km2']
print '+--- codigo_ibge: ' + jsonparsed['cidade_info']['codigo_ibge']
    
17.04.2017 / 02:42
2

Just to complement Guilherme Nascimento's answer, it is not necessary to import the json library, the requests itself already has a method that converts returns into json direct to dicts, as below:

import requests
CEP = 'http://api.postmon.com.br/v1/cep/'+ '01001001' 
r = requests.get(CEP)
print r.json()
    
17.04.2017 / 20:50