简体   繁体   中英

Flask jsonify: object is not iterable

I have a class looking like the following:

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

where SoundJsonSerializer enabling my custom JSONEncoder to serialize this object into JSON:

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

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

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

yields an error claiming s was not iterable which is true. How do I make the method return my wanted JSON?

I know I can do it by explicitly creating a dict from my Sound object like this:

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

But this seems really ugly to me. What's the preferred way to achieve my goal?

You could possibly try this work around:

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__)

You can do this a couple of different ways. The safest way to ensure that you only return what you want is to do it like this:

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))

By defining the name = None, length = None as part of the class level variables, you can use the vars() versus the __dict__

When you instantiate the class through the __init__ , and set the variables there, the jsonify will only return what you set via the __init__ .

Result with above code:

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

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