Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element by unknown key from jsonb in Postgres

I have following data structure:

{
    "proccess1": {
        "error": "error1 description",
        "nextRetryAt": "2018-02-22T07:39:00.325Z",
        "attemptsMade": 148,
        "firstFailedAt": "2018-02-16T06:40:41.327Z"
    },
    "proccess2": {
        "error": "error2 description",
        "nextRetryAt": "2019-03-16T06:41:01.566Z",
        "attemptsMade": 77,
        "firstFailedAt": "2016-03-15T04:35:12.248Z"
    }
}

My question is how to build query like

select * 
from data 
where data->[0]->>'nextRetryAt' = 'my passed value'

I don't know the names of keys proccess1 and proccess2. They might have any values.

like image 220
Daulet Nurgali Avatar asked Feb 22 '18 09:02

Daulet Nurgali


1 Answers

https://www.postgresql.org/docs/current/static/functions-json.html

jsonb_object_keys will help you

https://www.db-fiddle.com/f/9fB1pfb3BWv4v2wBUwU1Bd/0

with c(j) as (values('{
    "proccess1": {
        "error": "error1 description",
        "nextRetryAt": "2018-02-22T07:39:00.325Z",
        "attemptsMade": 148,
        "firstFailedAt": "2018-02-16T06:40:41.327Z"
    },
    "proccess2": {
        "error": "error2 description",
        "nextRetryAt": "2019-03-16T06:41:01.566Z",
        "attemptsMade": 77,
        "firstFailedAt": "2016-03-15T04:35:12.248Z"
    }
}'::jsonb))
select j->jsonb_object_keys(j)->>'nextRetryAt' from c;
like image 129
Vao Tsun Avatar answered Nov 06 '22 03:11

Vao Tsun