[英]Insert JSON String in to PostgreSQL table column
Trying to insert following JSON String as is without formatting 尝试按原样插入以下JSON字符串而不进行格式化
str={
"Trial": {
"@id": "xxxxx",
"key1": "aaaaaaaa (BAL-8557) aaaaaaaaaaaaaaaaaa",
"key2": "aaaaaaaaaaaaa , aaaaaaaaaaaaaaaaaaa",
"key3": "Yes",
"key4": "No",
"key5": {
"key5": [{
"@type": "ABC",
"$": "ABC121 "
},
{
"@type": "ABC",
"$": "ABC12133 "
}]
},
"Indications": {
"Indication": {
"@id": "1308",
"$": "aaaaaa"
}
}
}
}
in to following PostgreSQL DB 进入以下PostgreSQL数据库
CREATE TABLE records
(
id text,
record json
)
Code I am using to perform the insert operation 我用来执行插入操作的代码
cur = conn.cursor()
cur.execute("INSERT INTO trial_records(id, record) VALUES (%s, %s)", ('1', json.dumps(json.loads(str))))
Error I am getting 我收到错误
the JSON object must be str, bytes or bytearray, not 'dict'
Is this the right syntax to store json string as part of the column 这是将json字符串存储为列的正确语法吗
json.loads(obj)
creates json object from string data. json.loads(obj)
从字符串数据创建json对象。
json.dumps(obj)
creates string from json object. json.dumps(obj)
从json对象创建字符串。
So you should change json.dumps(json.loads(str))
to json.dumps(str)
. 因此,您应该将
json.dumps(json.loads(str))
更改为json.dumps(str)
。
PS: I'd also don't recommend to call your variables as type names like str
, int
. PS:我也不建议将变量称为
str
, int
等类型名称。 You are making str()
and int()
call unable from current scope. 您正在从当前作用域进行
str()
和int()
调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.