Flask jsonify: object not iterating

I have a class that looks like this:

class Sound(SoundJsonSerializer):
    def __init__(self, name, length):
        self.name = name
        self.length = length

where SoundJsonSerializer allows my custom JSONEncoder to serialize this object to JSON:

{
    "name": "foobar",
    "length": 23.4
}

Now I want one of my requests to exactly answer the above JSON.

@app.route('/sounds/<soundid>')
def get_sound(soundid):
    s = Sound("foobar", 23.4)
    return jsonify(s)

gives an error stating that sit was not iterable, which is true. How to force a method to return my JSON?

I know I can do this by explicitly creating a dict from my object Soundas follows:

    return jsonify({"name": s.name, "length": s.length})

But that seems really ugly to me. What is the preferred way to achieve my goal?

+4
source share
2 answers

You can try this work:

class Sound():
    def __init__(self, name, length):
        self.name = name
        self.length = length

@app.route('/sounds/<soundid>')
def get_sound(soundid):
    s = Sound('foobar', 23.4)
    return jsonify(s.__dict__)
+3

. , , , - :

class Sound():
    name = None
    length = None
    test = "Test"

    def __init__(self, name, length):
        self.name = name
        self.length = length

@admin_app.route('/sounds/<sound_id>')
def get_sound(sound_id):
    s = Sound('foobar', sound_id)
    return jsonify(vars(s))

= , length = None , vars() __dict__

__init__ , jsonify , __init__.

:

{
"length": "1",
"name": "foobar"
}
+2

All Articles