来自mysql的python中的JSON,带有其他键值对

时间:2017-09-12 11:50:02

标签: mysql python-3.x

这是用于从DB

获取数据的代码
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或将其附加到结果中。

2 个答案:

答案 0 :(得分:0)

您可以使用版本,用户类型和用户创建一个dict(键的位置' user'您输入行作为值)。然后使用json.dumpjson.dumps

将其转换为json
data = { "version": "5.2",  "user_type": "online",  "user":rows }

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

答案 1 :(得分:0)

只需将结果集包装在您喜欢的词典中。

# ...

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=(',', ': ')))

# ...