Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return JSON response from Python function

def addData():
    res = []
    class InfoData:
        def __init__(x, ID, number):
            x.ID = ID
            x.number = number

    for i in range(0, 10):
        res.append(InfoData("A",i))
        
    return json.dumps(res)
    #I got "Object of type InfoData is not JSON serializable"

I make an API using Flask Python and having a basic function above.

How can I return JSON response from this function ?

like image 342
Alex Avatar asked May 05 '26 22:05

Alex


1 Answers

Do it this way.

def addData():
    res = []
    class InfoData:
        def __init__(x, ID, number):
            x.ID = ID
            x.number = number

    for i in range(0, 10):
        res.append(InfoData("A",i).__dict__)
        
    return json.dumps(res)

like image 121
Stanley Ulili Avatar answered May 08 '26 13:05

Stanley Ulili



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!