TypeError: the JSON object must be str, not 'bytes' - Python - fixer.io

TypeError: the JSON object must be str, not 'bytes' - Python - fixer.io

我有这个代码:

from flask import Flask, flash, redirect, render_template, request, session, abort
import os
import json
from urllib.request import urlopen

tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
app = Flask(__name__, template_folder=tmpl_dir)

def getExchangeRates():
    rates = []
    response = urlopen('https://data.fixer.io/api/latest?access_key=my_key')
    data = response.read()
    rdata = json.loads(data, parse_float=float)

    rates.append( rdata['rates']['USD'] )
    rates.append( rdata['rates']['GBP'] )
    rates.append( rdata['rates']['HKD'] )
    rates.append( rdata['rates']['AUD'] )
    return rates

@app.route("/")
def index():
    rates = getExchangeRates()
    return render_template('test.html',**locals())      

@app.route("/hello")
def hello():
    return "Hello World!"

但它给我带来了这个:

Traceback (most recent call last):
File "/home/kristian/.virtualenvs/usio_flask/lib/python3.4/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/home/kristian/.virtualenvs/usio_flask/lib/python3.4/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/kristian/.virtualenvs/usio_flask/lib/python3.4/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/kristian/.virtualenvs/usio_flask/lib/python3.4/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/home/kristian/.virtualenvs/usio_flask/lib/python3.4/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/home/kristian/.virtualenvs/usio_flask/lib/python3.4/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "app/app.py", line 23, in index
rates = getExchangeRates()
File "app/app.py", line 13, in getExchangeRates
rdata = json.loads(data, parse_float=float)
File "/usr/lib/python3.4/json/__init__.py", line 312, in loads
s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'

违规行是这一行:

rdata = json.loads(data, parse_float=float)

我只是想从 fixer.io API 获取一些费率,有什么想法吗?

if name == "main": app.run()

[Python 3.Docs]: json.loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) 状态:

Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.

urllib.request.urlopen returns 一个 http.client.HTTPResponse 对象。

根据[Python 3.Docs]: http.client - HTTPResponse.read([amt])

Reads and returns the response body, or up to the next amt bytes.

因此,为了使这项工作有效,您必须将 bytes 转换为 str
(通过 [Python 3.Docs]: bytes.decode(encoding="utf-8", errors="strict")):

rdata = json.loads(data.decode(), parse_float=float)

:

  • Python 3.6开始,json.loads也能处理字节

关于您的其他错误,我记得(因为我曾经使用 FlaskResponse 对象只有一个 json 方法,如果 HTTP 状态码是 200确定)。但我不确定我们正在谈论的是同一个对象,因为我使用的是 requests 模块。