[英]Postgresql JSON column check key exists
I have wrote query like this to check json column has key我写了这样的查询来检查 json 列是否有键
SELECT *
FROM "details"
where ("data"->'country'->'state'->>'city') is not null;
but i need to write query which will select row if "data" contains "city"但我需要编写查询,如果“数据”包含“城市”,它将选择行
json structure of data is not consistent. json数据结构不一致。
You can check the top-level keys of data
with ?
您可以使用?
检查data
的顶级键as it is said in the documentation .正如 文档中所说。
For example例如
SELECT * FROM details
WHERE data ? 'city';
Checking every key in all nested objects from the json column requires a recursive CTE检查 json 列中所有嵌套对象中的每个键需要递归CTE
select * from details
where 'city' in (
WITH RECURSIVE t(k,j) as (
select jsonb_object_keys(details.data), details.data
UNION ALL
select jsonb_object_keys(t.j->t.k), t.j->t.k
FROM t WHERE jsonb_typeof(t.j->t.k) = 'object'
)
select k from t
);
This of course is not very efficient.这当然不是很有效。
You can use ?
你可以用?
: :
SELECT *
FROM "details"
WHERE data->'country'->'state' ? 'city';
You can convert your json to text and search for the key with LIKE您可以将 json 转换为文本并使用 LIKE 搜索密钥
SELECT *
FROM "details"
WHERE "data"::text LIKE '%"city":%'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.