json - Python query SQLite map values to column names -


i creating python script query sqlite db file. have connected sqlite db file , ran select query retrieve data.

the issue output missing column names.

import sqlite3 lite import sys import json  con = lite.connect('example.db')  con:          con.row_factory = lite.row          cur = con.cursor()         cur.execute("select * devices")          rows = cur.fetchall()          rowarray_list = []         row in rows:                 t = (row['id'], row['name'], row['type'])                 rowarray_list.append(t)          j = json.dumps(rowarray_list)         rowarrays_file = 'rowarrays.js'         f = open(rowarrays_file,'w')         print (f, j) 

here output of script.

<_io.textiowrapper name='rowarrays.js' mode='w' encoding='utf-8'> [[1, "example1", "computer"], [2, "example2", "server"], [3, "example3", "server"] 

below output required.

{"records":[{"id": "1", "name": "example1", "type": "computer"}, {"id": "2", "name": "example2", "type": "server"}, {"id": "3", "name": "example3", "type": "server"}]} 

since you're using sqlite3.row objects, you're aware have keys() method, returns list of column names. use that. try modifying part of code:

rowarray_list = [] row in rows:     d = dict(zip(row.keys(), row))   # dict column names keys     rowarray_list.append(d) 

Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -