简体   繁体   English

Python:jsonify中的str(bytes object)导致TypeError:“ bytes”类型的对象不可JSON序列化

[英]Python: str(bytes object) in jsonify causes TypeError: Object of type 'bytes' is not JSON serializable

I sent a request to my API but it throws TypeError: Object of type 'bytes' is not JSON serializable. 我向我的API发送了一个请求,但它引发TypeError:“字节”类型的对象不可JSON序列化。 It also returns a 500 INTERNAL SERVER ERROR. 它还返回500 INTERNAL SERVER ERROR。

Code: 码:

def login():
    data = request.json
    if(data['token'] != 'xxxxxxxxxxx'):
        return jsonify(), 401
    user = User.objects(npm=data['npm']).first()
    if(user == None):
        del data['token']
        user = User(**data)
        user.major = Major.objects(name=data['major']).first()
        user.role = 'user'
        user.save()
    token = jwt.encode({
        'user_id': str(user.id)
    }, secret_key, algorithm='HS256')
    return jsonify({
        'user_id': str(user.id),
        'token': token,
        'major_id': str(user.major.id)
    }), 200

Traceback: 追溯:

Traceback (most recent call last):
File "c:\users\anisha\env\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "c:\users\anisha\env\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "c:\users\anisha\env\lib\site-packages\flask_cors\extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "c:\users\anisha\env\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "c:\users\anisha\env\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "c:\users\anisha\env\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "c:\users\anisha\env\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "c:\users\anisha\env\lib\site-packages\flask_cors\decorator.py", line 128, in wrapped_function
resp = make_response(f(*args, **kwargs))
File "C:\Users\Anisha\sunjadv2-server\app.py", line 69, in login
'major_id': str(user.major.id)
File "c:\users\anisha\env\lib\site-packages\flask\json\__init__.py", line 321, in jsonify
dumps(data, indent=indent, separators=separators) + '\n',
File "c:\users\anisha\env\lib\site-packages\flask\json\__init__.py", line 179, in dumps
rv = _json.dumps(obj, **kwargs)
File "C:\Users\Anisha\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Users\Anisha\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\Anisha\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "c:\users\anisha\env\lib\site-packages\flask\json\__init__.py", line 81, in default
return _json.JSONEncoder.default(self, o)
File "C:\Users\Anisha\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", line 180, in default
o.__class__.__name__)
TypeError: Object of type 'bytes' is not JSON serializable

When I do print("major_id: " + str(user.major.id)) it will print major_id: 5b55e986f15bf336e0b820fe to console. 当我执行print("major_id: " + str(user.major.id)) ,它将对控制台输出major_id:5b55e986f15bf336e0b820fe Why does str(user.major.id) seen as bytes type in jsonify? 为什么在jsonify中将str(user.major.id)视为字节类型? I've tried to delete 'major_id': str(user.major.id) but then line 'token': token will cause the same error. 我试图删除'major_id': str(user.major.id)但随后的行'token': token将导致相同的错误。

Thank you. 谢谢。

It seems that your data may not be properly decoded. 看来您的数据可能未正确解码。 You could try to decode your data before jsonifying it. 您可以在对数据进行json解码之前尝试对其进行解码。

For example, instead of using token directly, try using: token.decode('utf-8') 例如,代替直接使用令牌,请尝试使用: token.decode('utf-8')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python TypeError:“字节”类型的对象不是 JSON 可序列化的 - Python TypeError: Object of type 'bytes' is not JSON serializable JSON 和 Python 的密码术:TypeError:Object 字节类型不是 Z0ECD11C148A23BBD7A2 - JSON and Cryptography With Python: TypeError: Object of type bytes is not JSON serializable “ TypeError:字节类型的对象不可JSON序列化” - “TypeError: Object of type bytes is not JSON serializable” Celery - 类型错误:字节类型的 Object 不是 JSON 可序列化 - Celery - TypeError: Object of type bytes is not JSON serializable 类型错误:“字节”类型的 Object 不是 JSON 可序列化 - TypeError: Object of type 'bytes' is not JSON serializable 字节类型的 Object 不是 JSON 可序列化的 - Object of type bytes is not JSON serializable 字节类型的对象不是 JSON 可序列化的 - Object of type bytes is not JSON serializable 如何修复“ TypeError:字节类型的对象不可JSON序列化” - How to fix 'TypeError: Object of type bytes is not JSON serializable' 请如何解决此错误 - TypeError: Object of type bytes is not JSON serializable - How to fix this error please - TypeError: Object of type bytes is not JSON serializable 如何处理 TypeError: 'bytes' 类型的对象不是 JSON 可序列化的? - How to deal with TypeError: Object of type 'bytes' is not JSON serializable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM