Search code examples
pythonpostgresqlasyncpg

asyncpg. What is the right way to convert a record to JSON


I have some method which responsible for getting data from some table by id. This data comes in string format. I need convert them to json.

async def my_async_method():
    conn = await asyncpg.connect(**db_conf)
    row = await conn.fetchrow(
        'SELECT database.schema.table.some_table '
        'FROM database.schema.some_table'
        'WHERE database.schema.some_table.id = $1')
    import_transaction = json.loads(row[0])
await conn.close()

loop = asyncio.get_event_loop()
loop.run_until_complete(my_async_method())

What is the right way to converts data from string to json, in case of usage asyncpg? I Will be grateful for the help.


Solution

  • You cannot simply parse a random string into JSON format, unfortunately.

    JSON is a syntax, learn up on it here https://www.json.org/

    You are most likely going to want to build the json string yourself from the table column names and values of row[0].

    Good luck!