How to fix Requests encoding in Python?

Asked

Viewed 1,670 times

2

I’m studying Requests in Python and I’m trying to get the data from the zip code: http://api.postmon.com.br/v1/cep/

I can pick up, but when it comes time to show them, how I live in São Paulo because of the encoding I get: S\u00e3o Paulo

Reading the requests tab (http://docs.python-requests.org/pt_BR/latest/user/quickstart.html#respota-json) I know it’s possible to fix it using r.encoding, but I’m not getting it. What I’m 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

Upshot:

{"complement": "lado par", "bairro": "S u00e9", "cidade": "S u00e3o Paulo", "logradouro": "Pra u00e7a da S u00e9", "estado_info": {"area_km2": "248.221,996", "codigo_ibge": "35", "name": "S u00e3o Paulo"}, "cep": "01001001", "cidade_info": {"area_km2": "1521,11", "codigo_ibge": "3550308"}, "estado": "SP"}

2 answers

4

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

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

3


That one \u is an "escape" used in JSON and Javascript for non-ASCII characters (by default Json uses Unicode), in case you returned as a string, then it maintains the use of this to avoid character loss.

To get the seats just do the "parse" (https://docs.python.org/2/library/json.html) of 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']

Browser other questions tagged

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