I have a table in Postgres 14.9:
Name (Txt) | Detail (JSONB) | state (JSONB) |
---|---|---|
apple | [{ "code": "156", "color": "red" }, { "code": "156", "color": "blue" }] | [{ "ap": "good", "op2": "bad" }] |
orange | [{ "code": "156", "color": "red" }, { "code": "235", "color": "blue" }] | [{ "op": "bad", "op2": "best" }] |
lemon | [{ "code": "156", "color": "red" }, { "code": "156", "color": "blue" }] | [{ "cp": "best", "op2": "good" }] |
I want this select sql output :
Name (Txt) | Detail (JSONB) | state (JSONB) |
---|---|---|
apple | { "code": "156", "color": "red"} | { "ap": "good", "op2": "bad" } |
apple | { "code": "156", "color": "blue"} | { "ap": "good", "op2": "bad" } |
orange | { "code": "156", "color": "red" } | { "op": "bad", "op2": "best" } |
lemon | { "code": "156", "color": "red" } | { "cp": "best", "op2": "good" } |
lemon | { "code": "156", "color": "blue"} | { "cp": "best", "op2": "good" } |
My attempt:
SELECT
"Name (Txt)"
, jsonb_build_object('code', elem->>'code', 'color', elem->>'color') AS "Detail (JSONB)"
, state::JSONB "
FROM your_table,
jsonb_array_elements("Detail (JSONB)") AS elem,
state::JSONB
WHERE elem->>'code' = '156';
3
Answers
Welcome to stackoverflow
Considering
yellow
in your output is a typo.I have a table with the name
test_table
. Schema of the table isFollowing query will give the desired output.
You could unnest your array with
JSONB_TO_RECORDSET
, then remap your json objects withJSONB_BUILD_OBJECT
."Output":
Check the demo here.
jsonb_array_elements()
does exactly what you are asking for, in a single step:fiddle
See:
If there can be empty arrays or
null
indetail
, here is a variant to preserve all input rows:See:
Of course,
detail
must be a jsonb array, or you get an error. You might test withjsonb_typeof()
first:See: