1

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)
2
  • 3
    Please post your code as text instead of image. Commented Feb 17, 2020 at 15:23
  • If you only need the "_id", "name" and "nachname" property, you could just create a dict with those values instead of the "Mitarbeiter" class. If you need the class though, you could let it inherit from dict. This way you could pass just "z" to json.dumps as z would be a dict-like object Commented Feb 17, 2020 at 15:34

1 Answer 1

7

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])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.