简体   繁体   中英

Dynamically add data to JSON response

I have a RESTful API, which returns all elements of a database table in a JSON format. I'd need to display the individual links/ids in the collection+json.

@app.route('/table/showall/<table>', methods = ['GET'])
def api_showAll(table) -> str:
    if request.method == 'GET':
        with DBcm.UseDatabase(DBconfig) as cursor:

            _SQLlist = "SELECT * FROM %s;" % table
            cursor.execute(_SQLlist)
            data = cursor.fetchall()


Links = { "collection" :
            {
                "hrefs" : 
                    [
                        { "href": "127.0.0.1:5000/table/showone/tableNam/id"},
                        { "href": "127.0.0.1:5000/table/showone/tableNam/id"},
                        { "href": "127.0.0.1:5000/table/showone/tableName/id"}
                    ]
                }
    }

return json.dumps(str(Links))

Since the data in the database will grow over time due to inserts, how would I dynamically add individual items into a JSON to show on the screen? Above you can see what I've tried so far. It shows 3 values hard-coded but I'd need to do it dynamically.

Any help appreciated

创建一个复制模型并使其可json serializable的类,然后可以使用json.dumps(object) ,在此处找到可能的解决方案代码如何使JSON可序列化的类

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