[英]Inserting nested json into a column in Postgres
I'm writing an insert function and I have a nested dictionary that I want to insert into a column in postgres, is there a way to insert the whole json into the column? 我正在写一个插入函数,我有一个嵌套的字典要插入到postgres的列中,有没有办法将整个json插入到列中? Lets say I have to insert the value of the key "val" into a column, how can I achieve that? 可以说我必须将键“ val”的值插入列中,如何实现呢? I'm using psycopg2 library in my python code. 我在python代码中使用了psycopg2库。
"val": {
"name": {
"mike": "2.3",
"roy": "4.2"
}
}
Yes, you can extract nested JSON using at least Postgres 9.4 and up by casting your string to JSON and using the "Get JSON object field by key" operator: 是的,您可以至少使用Postgres 9.4及更高版本来提取嵌套的JSON,方法是将字符串转换为JSON并使用“按键获取JSON对象字段”运算符:
YOUR_STRING ::CAST JSON_OPERATOR
'{"val":1}' ::JSON -> 'val'
This works in at least Postgres 9.4 and up: 至少在Postgres 9.4及更高版本中可以使用:
INSERT INTO my_table (my_json)
VALUES ('"val":{"name":{"mike":"2.3"}}'::JSON->'val');
Depending on your column type you may choose to cast to JSONB instead of JSON (the above will only work for TEXT and JSON). 根据您的列类型,您可以选择强制转换为JSONB而不是JSON(以上内容仅适用于TEXT和JSON)。
INSERT INTO my_table (my_json)
VALUES ('"val":{"name":{"mike":"2.3"}}'::JSONB->'val');
See: https://www.postgresql.org/docs/9.5/static/functions-json.html 参见: https : //www.postgresql.org/docs/9.5/static/functions-json.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.