这是用于从数据库获取数据的代码

import pymysql

import json



     conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', db='test', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM user")

    rows = []
    for row in cursor:
        rows += [row]

    print(json.dumps(rows, sort_keys=False, indent=4, separators=(',', ': ')))

    cursor.close()
    conn.close()


json中的输出是-

[
    {
        "name": "John",
        "id": 50
    },
    {
        "name": "Mark",
        "id": 57
    }
]


但是我想要这种格式的输出-

{
    "version": "5.2",
    "user_type": "online",
    "user":
    [
        {
            "name": "John",
            "id": 50
        },
        {
            "name": "Mark",
            "id": 57
        }
    ]
}


其中版本和user_type可以手动输入或附加到结果中。

最佳答案

只需将结果集包装成您喜欢的字典即可。

# ...

cursor.execute("SELECT * FROM user")
response = {
    "version": "5.2",
    "user_type": "online",
    "user": list(cursor),  # This is equivalent to iterating over the cursor yourself.
}
print(json.dumps(response, sort_keys=False, indent=4, separators=(',', ': ')))

# ...

关于mysql - 来自mysql的python中的JSON和其他键值对,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46175635/

10-10 16:33