简体   繁体   中英

Python Converting List of Objects to JSON String

I am trying to parse a List of Python Objects to a Json String. I have a list of a Python objects called "list_mitarbeiter". In this List are Objects of Mitarbeiter:

class Mitarbeiter:
    def __init__(self, _id, name, nachname):
        self._id = _id
        self.name = name
        self.nachname = nachname

i try to parse the list_mitarbeiter to a JSON String with:

x = json.dumps(z.__dict__ for z in list_mitarbeiter)

Everytime i try this, i am getting an Error: Object of type generator is not JSON serializable

I already did it with only 1 object of the list and it worked, i dont understand why it isnt working when i am doing it with the for Loop for each Object in list_mitarbeiter.

x = json.dumps(list_mitarbeiter[1]. dict ) ^^ this is working

Here is my whole Code:

rom pymongo import MongoClient
from flask import Flask
import json

app = Flask(__name__)

class Mitarbeiter:
    def __init__(self, _id, name, nachname):
        self._id = _id
        self.name = name
        self.nachname = nachname



@app.route('/getallmitarbeiter')
def index():
    cluster = MongoClient("<CONNECTON STRING>")
    db = cluster["DP_0001"]
    collection = db["Mitarbeiter"]

    mitarbeiter = collection.find({})

    list_mitarbeiter = []

    for worker in mitarbeiter:
        test1 = Mitarbeiter(worker["_id"], worker["name"], worker["nachname"])
        list_mitarbeiter.append(test1)

    x = json.dumps(z.__dict__ for z in list_mitarbeiter)
    return x


if __name__ == '__main__':
    app.run(debug=True)

JSON can't encode generators, it needs strings, numbers, bools, None, tuples, lists, or dictionaries. Just convert your generator comprehension into a list comprehension and it will work:

x = json.dumps([z.__dict__ for z in list_mitarbeiter])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM