-1

Simple table in PostgreSQL 12.3

create table aaa(id integer, data json);

In data column stores JSON with the following form:

{
    "foo": 1,
    "persons": [
        {
            "name": "2fdsdsd",
            "test": {
                "id": "123",
                "age": 32
            }
        }
    ],
    "some_prop": "123"
}

I need to find all records from aaa where test.id = '123' or where test = null.

1
  • It's integer not indeger. Your example json is invalid because of unmatched quotes. Are you actually using json type or jsonb? What have you tried so far? By second one you mean those records where test.id is either '123' or null? Commented Oct 9, 2023 at 19:08

1 Answer 1

1

If that's jsonb, you can use @? operator with a jsonpath: demo

select id, jsonb_pretty(data) from aaa
where data @? '$.persons[*].test?(@.id=="123" || @==null)';

Which means roughly

  1. Take what's under persons key
  2. Assume it's an array and inspect all its elements
  3. In each element check test key
  4. Under test, see if value for key id is '123' or if the whole test is null.

If it's a plain json, you can cast it:

select id, jsonb_pretty(data::jsonb) from aaa
where data::jsonb @? '$.persons[*].test?(@.id=="123" || @==null)';
Sign up to request clarification or add additional context in comments.

1 Comment

this is exactly what i need, tnx @Zegarek

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.