Search code examples
postgresqljsonb

how to get from jsonb subJesonb by key array in postgres


I have jsonb field and array keys how get sub jsonb

field = {"f1":1, "f2":null, "f3":"fff", "f4":"4"}

kes = ["f1", f3]

We need to get: {"f1":1, "f3":"fff"}


Solution

  • You could unnest both, join the results and aggregate back:

    Something like:

    select jsonb_object_agg(i.k, i.v)
    from jsonb_each('{"f1":1, "f2":null, "f3":"fff", "f4":"4"}'::jsonb) as i(k,v)
      join jsonb_array_elements_text('["f1", "f3"]') t(k) on t.k = i.k