[英]Querying JSON dynamically with PostgreSQL
I have a json value like the below which I am wanting to extract details from in a PostgreSQL Database.我有一个类似于下面的 json 值,我想从 PostgreSQL 数据库中提取详细信息。
[{"monday":{"opens":730,"closes":2300}},{"tuesday":{"opens":730,"closes":2300}},{"wednesday":{"opens":730,"closes":2300}},{"thursday":{"opens":730,"closes":2300}},{"friday":{"opens":730,"closes":2300}},{"saturday":{"opens":730,"closes":2300}},{"sunday":{"opens":730,"closes":2300}}]
Currently I am using the following syntax to extract opening hours which returns '730' in this instance目前我正在使用以下语法来提取开放时间,在这种情况下返回“730”
s.opening_hours -> 0 -> 'monday' ->> 'opens'
However I want it to be more dynamic by being able to obtain opening hours without specifying 'Monday' as sometimes the value does not start with Monday, eg sometimes 'Tuesday'.但是,我希望它能够在不指定“星期一”的情况下获得开放时间,从而使其更具动态性,因为有时该值不从星期一开始,例如有时“星期二”。
Attempts so far to replace 'Monday' with the number position have return 'null' eg到目前为止,用数字位置替换“星期一”的尝试返回“空”,例如
s.opening_hours -> 0 -> 0 ->> 'opens' , -- null
Well, you could do a lateral join with a derived table getting the first key of the object in question using jsonb_object_keys() WITH ORDINALITY
ans use that key in your expression.好吧,您可以使用
jsonb_object_keys() WITH ORDINALITY
与派生表进行横向连接,获取相关对象的第一个键,并在表达式中使用该键。
SELECT t.opening_hours->0->x.k->'opens'
FROM (VALUES ('[{"monday":{"opens":730,"closes":2300}},{"tuesday":{"opens":730,"closes":2300}},{"wednesday":{"opens":730,"closes":2300}},{"thursday":{"opens":730,"closes":2300}},{"friday":{"opens":730,"closes":2300}},{"saturday":{"opens":730,"closes":2300}},{"sunday":{"opens":730,"closes":2300}}]'::jsonb)) AS t
(opening_hours)
CROSS JOIN LATERAL (SELECT jok.k
FROM jsonb_object_keys(t.opening_hours->0) WITH ORDINALITY jok
(k,
o)
ORDER BY jok.o
LIMIT 1) x;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.