首页 > 解决方案 > 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()

标签: pythonflask

解决方案


您的用户对象不是可迭代类型。通常,数据库模型不是。您需要更改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"}]}

推荐阅读