我需要通过jsonb_set更新jsonb列,要使用jsonb_set,需要一个完整的Json路径。当 jsonb 有列表时,如何获得完整的 jsonb 路径?
例如,我得到了一个 JSON :
{
"Laptop": {
"brand": "Dell",
"price": 1200,
"specs": [
{
"name": "CPU",
"Brand": "Intel"
},
{
"name": "GPU",
"Brand": "Nvdia"
},
{
"name": "RAM",
"Brand": "Kingston"
}
]
}
}
我需要一些类似的查询
SELECT <full_path>
FROM table
WHERE jsonb_path_query_first(col,"$.Laptop.specs[*].name")::text='"CPU"'`;
我需要一个与上面的查询匹配的完整路径 回报可能是
$.Laptop.specs[0].name
甚至更好{Laptop,specs,0,name}
在Postgres中有什么方法可以实现这一点吗?
根据我的理解,你需要路径的索引?让我知道
WITH json_data AS (
SELECT '{"Laptop": {"brand": "Dell", "price": 1200, "specs": [{"name": "CPU", "Brand": "Intel"}, {"name": "GPU", "Brand": "Nvdia"}, {"name": "RAM", "Brand": "Kingston"}]}}'::jsonb AS col
)
SELECT
CONCAT('$.Laptop.specs[', idx - 1, '].name') AS full_json_path
FROM
json_data,
LATERAL jsonb_array_elements(col->'Laptop'->'specs') WITH ORDINALITY arr(elem, idx)
WHERE
elem->>'name' = 'CPU';
输出
$.Laptop.specs[0].name