python - Python:尝试使用 dict 创建 json 对象(TypeError:无法解压不可迭代的用户对象)
问题描述
我正在尝试从模块返回一个完整的 JSON 对象,该模块从数据库中获取所有用户并将他们的数据输入到一个 JSON 对象中,但是我得到TypeError: cannot unpack non-iterable User object
了,我真的不知道问题出在哪里。
from application.models import User
class users_eng:
def __init__(self):
pass
def get_users(self):
users = User.query.all()
# users output - [<User 9nematix>, <User 3nematix>, <User 6nematix>]
for user in users:
users_data = {
dict(
username=user.username,
bio=user.profile_bio,
role=user.role,
profile_picture=user.profile_picture
) for user.username, user.profile_bio, user.role, user.profile_picture, *_ in users
}
x = json.dumps(users_data)
print(x)
return x
_users_ = users_eng()
** 编辑:我用评论中的其他解决方案更新了我的代码,但现在我得到了[<generator object users_eng.get_users.<locals>.<genexpr> at 0x000001AF38C828C8>]
from application.models import User
from flask import session
import json
class users_eng:
def __init__(self):
pass
def get_users(self):
users = [
User.query.all()
]
# users output - [<User 9nematix>, <User 3nematix>, <User 6nematix>]
users_data = []
for user in users:
users_data.append(
dict(
username=user.username,
bio=user.profile_bio,
role=user.role,
profile_picture=user.profile_picture,
) for user in users
)
print(users_data)
return users_data
_users_ = users_eng()
解决方案
您的用户对象不是可迭代类型。通常,数据库模型不是。您需要更改for user.username user.bio ...
为for user
此外,dicts 是不可散列的,因此在修复第一个错误后您会遇到另一个错误。我建议您制作users_data
一个字典数组,而不是字典
例子:
# Ignore this, substitute with your own model
from database.models import User
users = [
User(email="foo@bar.com", first="Foo", last="Bar")
]
users_data = [
dict(
email=user.email,
name=f"{user.first} {user.last}",
) for user in users
]
将其转换回有效 JSON 对象的附加示例
from json import dumps
from database.models import User
users = [
User(email="foo@bar.com", first="Foo", last="Bar")
]
users_data = [
dict(
email=user.email,
name=f"{user.first} {user.last}",
) for user in users
]
# This is valid JSON
rv = dumps({"users": users_data})
print(rv)
输出:
{"users": [{"email": "foo@bar.com", "name": "Foo Bar"}]}
推荐阅读
- teradata - 如何修剪 teradata 表列中的尾随空格
- ruby - 对于 Rails,使用手写迁移创建“ar_internal_metadata”表是个好主意吗?
- amazon-web-services - AWS EC2 实例登录失败
- osgi - osgi 未解决的需求:osgi.native
- vba - 批量打印来自多封电子邮件的同名附件
- ios - 如何只为 iPhone X 在顶部添加额外的高度?
- mysql - 有两个表Mysql的条件查询
- jquery - 不允许用户取消选择 WooCommerce 中的变体
- c# - ASP.NET Core 2 Windows 身份验证/AD 获取组成员
- python - 输出中的进度条取决于 Python 中的计算进度