Python 如何在postgreSQL中插入/更新JSON数据

Python 如何在postgreSQL中插入/更新JSON数据,python,json,postgresql,psycopg2,Python,Json,Postgresql,Psycopg2,这是我的表模式 [column] [type] tablename json word varchar text json 我在Python中使用psycopg2实现 cur.execute("INSERT INTO json (word,text) VALUES (%s,%s);",(word,text)) word包含列表对象类型,但内部为字符串 ['a','b','c'] 文本包含列表对象类型,但内部是dict(json) 当我运行函数时。我在下面发现

这是我的表模式

[column] [type]
tablename json  
word  varchar  
text  json
我在Python中使用psycopg2实现

cur.execute("INSERT INTO json (word,text) VALUES (%s,%s);",(word,text))
word包含列表对象类型,但内部为字符串

['a','b','c']
文本包含列表对象类型,但内部是dict(json)

当我运行函数时。我在下面发现了这个错误

" can't adapt type 'dict' "
问题是,如何将json插入到postgreSQL中,正如您看到的文本类型一样。它看起来像dict,但如何分配文本变量是json?。或者我遗漏了什么?

json.dumps()
可用于切换到数据库的字符串

import json
postgres_string = json.dumps(text)
# Save postres_string into postgress here

# When you want to retrieve the dictionary, do so as below:
text = json.loads(postgres_string)

好的,您可以使用
execute
函数来执行SQL,只要构造正确的SQL,它就会成功。要插入json类型的数据,只需使用“::”将字符串类型转换为json类型,如下所示:

postgres=# insert into json_test(word,text) values('abcd_word','[{"a":"b"},{"c":"d"}]'::json);
INSERT 0 1
postgres=# 
postgres=# select * from json_test ;
 tablename |   word    |         text          
-----------+-----------+-----------------------
           | abcd_word | [{"a":"b"},{"c":"d"}]
postgres=# insert into json_test(word,text) values('abcd_word','[{"a":"b"},{"c":"d"}]'::json);
INSERT 0 1
postgres=# 
postgres=# select * from json_test ;
 tablename |   word    |         text          
-----------+-----------+-----------------------
           | abcd_word | [{"a":"b"},{"c":"d"}]