TypeError:JSON对象必须为str,而不是'bytes'-Python-fixer.io

时间:2018-08-15 16:09:08

标签: 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中获得一些收益,有什么想法吗?

如果名称 ==“ 主要”:     app.run()

1 个答案:

答案 0 :(得分:2)

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

  

使用此str将s(包含JSON文档的conversion table实例)反序列化为Python对象。

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

根据[Python 3.5]: HTTPResponse.read([amt])

  

读取并返回响应正文,或直至下一个 amt 字节

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

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

注意

  • Python 3开始。 6 json.loads还能处理字节

关于您的其他错误,我记得(当我曾经与 Flask 一起工作过),{<1>}对象只有Response方法,如果 HTTP < / em>状态代码为 200 确定)。但由于我使用的是 requests 模块,所以我不确定它与我们正在讨论的对象是同一对象。