JSON in python from mysql with additional key value pairs -
this code used fetch data 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 * user") rows = [] row in cursor: rows += [row] print(json.dumps(rows, sort_keys=false, indent=4, separators=(',', ': '))) cursor.close() conn.close() output in json -
[ { "name": "john", "id": 50 }, { "name": "mark", "id": 57 } ] but want output in format -
{ "version": "5.2", "user_type": "online", "user": [ { "name": "john", "id": 50 }, { "name": "mark", "id": 57 } ] } where version , user_type can manually entered or appended result.
simply wrap result set in dict of liking then.
# ... cursor.execute("select * user") response = { "version": "5.2", "user_type": "online", "user": list(cursor), # equivalent iterating on cursor yourself. } print(json.dumps(response, sort_keys=false, indent=4, separators=(',', ': '))) # ...
Comments
Post a Comment