MrOldSir
MrOldSir

Reputation: 726

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.

Upvotes: 6

Views: 10441

Answers (2)

0asa
0asa

Reputation: 224

You should be able to cast your result to a dict, according to this issue: https://github.com/MagicStack/asyncpg/issues/263

Upvotes: 4

randy
randy

Reputation: 166

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!

Upvotes: 4

Related Questions