[英]json object query in postgresql
I am working with a row that contains JSON data.我正在处理包含 JSON 数据的行。 the column is like this,
专栏是这样的
log
[{{"status":"orderderd","date":"2021-10-13T16:30:57.134Z"},{"status":"deivered","date":"2021-10-13T16:30:57.134Z"}}]
now I want to get the time when the status is delivered.现在我想获得状态交付的时间。 How can I write a query for this?
我该如何为此编写查询?
If you are using Postgres 12 or later, you can do this quite easily using a JSON path query:如果您使用的是 Postgres 12 或更高版本,则可以使用 JSON 路径查询轻松完成此操作:
select jsonb_path_query_first(log, '$[*] ? (@.status == "delivered").date') #>> '{}' as delivery_date
from the_table;
jsonb_path_query_first
returns a jsonb
value and the expression #>> '{}'
turns that into a text value. jsonb_path_query_first
返回一个jsonb
值,表达式#>> '{}'
将其转换为文本值。
If you are using an older version, you need to unnest the array:如果您使用的是旧版本,则需要取消嵌套数组:
select (select l.element ->> 'date'
from jsonb_array_elements(t.log) as l(element)
where l.element ->> 'status' = 'delivered'
limit 1) as delivery_date
from the_table t;
Both queries assume that the column is defined as jsonb
(which it should be).两个查询都假定该列被定义为
jsonb
(它应该是)。 If it's not you need to cast it (eg log::jsonb
)如果不是,则需要对其进行转换(例如
log::jsonb
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.