[英]How to change the name of a key in a JSON object stored in Postgres for all records
In a table called priceTables
I am storing in a column named value
a JSON object that looks something similar to this:在名为priceTables
的表中,我在名为value
的列中存储了一个 JSON 对象,该对象类似于以下内容:
{
"price": {
"values": {
"tax": 1.59
}
}
}
And would like to run a query to migrate tens of thousands of records to change the name of values
to breakdown
.并且想运行一个查询来迁移数以万计的记录以将values
的名称更改为breakdown
。 So it will result in所以会导致
{
"price": {
"breakdown": {
"tax": 1.59
}
}
}
Any suggestions on the Postgres query for achieving this?关于实现这一点的 Postgres 查询有什么建议吗?
If the name can only occur once in the JSON or if all occurrences should be replaced if there are more, a quick and dirty one is a simple replace()
in the text:如果名称只能在 JSON 中出现一次,或者如果出现更多,则所有出现的地方都应该被替换,一个快速而肮脏的方法是文本中的简单replace()
:
UPDATE elbat
SET value = replace(value::text, '"values"', '"breakdown"')::jsonb;
(Replace jsonb
with json
if the type of the column is json
rather than jsonb
.) (替换jsonb
与json
如果列类型是json
而非jsonb
。)
This should work.这应该有效。
UPDATE priceTables
SET value = value || jsonb_build_object(
'price',
jsonb_build_object(
'breakdown',
priceTables.value #> '{price,values}'
)
)
WHERE priceTables.value #> '{price,values}' IS NOT NULL;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.