You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm trying to use a json_agg() function of PostgreSQL with python and asyncpg. The data returned is a list of just one element that begins with <Record jsonb_agg= string and than a correct json.
I'd like to have the json string directly from the DB and not use the "workaround" in the code. Is something wrong in my code?
"""Example PostgreSQL JSON with asyncpg"""importasyncioimportjsonimportasyncpgfrompydanticimportBaseModel, ValidationErrorDSN="postgresql://postgres:[email protected]/testdb"QUERY='select jsonb_agg(t) from (select * from "tmp") t;'asyncdeffetch_data_from_db():
"""get data from DB."""conn=awaitasyncpg.connect(DSN)
result=awaitconn.fetch(QUERY)
awaitconn.close()
returnresultasyncdefget_list():
"""Get List"""result=awaitfetch_data_from_db()
returnresultclassPerson(BaseModel):
"""Person model."""id: intname: strsurname: str@classmethoddefparse_from_json(cls, json_data):
"""Parse from json."""try:
returncls(**json.loads(json_data))
exceptValidationErrorase:
raiseValueError(f"Error: {str(e)}")
asyncdefmain():
result_raw=awaitget_list()
### this is a workaround ###element=result_raw[0]
json_string=element["jsonb_agg"]
json_result=json.loads(json_string)
#####################print(f"type and len of result_raw: {type(result_raw)}/{len(result_raw)}")
print(f"type and len of json_result: {type(json_result)}/{len(json_result)}")
try:
persona_data=json_result[0]
persona=Person(**persona_data)
print("Valid JSON object:", persona)
exceptValueErrorase:
print(e)
if__name__=='__main__':
loop=asyncio.get_event_loop()
loop.run_until_complete(main())
type and len of result_raw: <class 'list'>/1
type and len of json_result: <class 'list'>/3
Valid JSON object: id=8 name='Donald' surname='Duck'
CREATETABLE "public"."tmp" (
"id"integerNOT NULL,
"name" character varying NOT NULL,
"surname" character varying NOT NULL,
CONSTRAINT"tmp_pkey"PRIMARY KEY ("id")
);
INSERT INTO"tmp" ("id", "name", "surname") VALUES
(8, 'Donald', 'Duck'),
(9, 'Daisy', 'Duck'),
(10, 'Scrooge', 'McDuck');
select*from tmp;
id | name | surname
----+---------+---------8 | Donald | Duck
9 | Daisy | Duck
10 | Scrooge | McDuck
(3 righe)
I expect a json valid string in result_raw
The text was updated successfully, but these errors were encountered:
I'm trying to use a
json_agg()
function of PostgreSQL with python and asyncpg. The data returned is alist
of just one element that begins with<Record jsonb_agg=
string and than a correct json.I'd like to have the json string directly from the DB and not use the "workaround" in the code. Is something wrong in my code?
I expect a json valid string in
result_raw
The text was updated successfully, but these errors were encountered: