G
G
Gleb Lukashonok2021-11-02 19:28:39
Python
Gleb Lukashonok, 2021-11-02 19:28:39

How to convert to the next value?

Hello! After querying the database, I get the following response:

query = [
    (5116, 'Пользователь', 'Тестовая группа', '32 ВСЕГДА', None, '123', '100CF89C4', datetime.datetime(2021, 1, 12, 0, 0), datetime.datetime(2050, 1, 15, 0, 0)),
    (5117, 'NFC_TEST', 'Сотрудники', 'Суббота', None, None, '2CFF344', datetime.datetime(2021, 1, 16, 0, 0), None),
    (5118, 'Hleb', 'Сотрудники', '32 ВСЕГДА', None, None, '14E5F48', datetime.datetime(2021, 2, 17, 0, 0), None)
    ]

How to convert this to a JSON of the form or a Python array:
query = [
    {
        "id": 5116,
        "name": 'Пользователь',
        "group": 'Тестовая группа',
        "access": '32 ВСЕГДА',
        "description": '123',
        "card": '100CF89C4',
        "first_date": "datetime.datetime(2021, 1, 12, 0, 0)",
        "second_date": "datetime.datetime(2050, 1, 15, 0, 0))",
    },
    {
        "id": 5117,
        "name": 'NFC_TEST',
        "group": 'Сотрудники',
        "access": None,
        "description": None,
        "card": '2CFF344',
        "first_date": "datetime.datetime(2021, 1, 16, 0, 0)",
        "second_date": None,
    },
    {
        "id": 5118,
        "name": 'Hleb',
        "group": 'Сотрудники',
        "access": '32 ВСЕГДА',
        "description": None,
        "card": '100CF89C4',
        "first_date": "datetime.datetime(2021, 2, 17, 0, 0)",
        "second_date": None,
    }
]

Sorry for the stupid question, thanks!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
ScriptKiddo, 2021-11-02
@Bombesko

For SQLite

import sqlite3

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

con = sqlite3.connect(":memory:")
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print cur.fetchone()["a"]

https://stackoverflow.com/a/3300514
For Firebird
Table content
6181b8910e3d4214511286.png
import fdb

con = fdb.connect(dsn='127.0.0.1:/firebird/data/test.db',
                  port=3050,
                  user='test_user',
                  password='76d8bf4f81598b847170')

cur = con.cursor()
cur.execute("select * from NEWTABLE order by NAME")

def dict_cursor(cursor):
    column_names = [x[0] for x in cursor.description]
    for row in cursor:
        yield {key: value for key, value in zip(column_names, row)}


for item in dict_cursor(cur):
    print(item)

{'NAME': 'Ivan', 'SURNAME': 'Ivanov'}
{'NAME': 'Petr', 'SURNAME': 'Petrov'}

A
aRegius, 2021-11-03
@aRegius

keys = ('id', 'personal_number' ...)
data = [dict(zip(keys, values)) for values in query]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question