1

In a postgres table I have some jsonb in this format

[{"type": "pet", "animal": "cat"}, {"type": "farm", "animal": "cow","colour": "brown"}]

But I want to turn it into this format

{"cat": {"type": "pet", "animal": "cat"}, "cow" {"type": "farm", "animal": "cow", "colour": "brown"}

And I can't figure it out or find anyone on the internet who has jsonb in this format. Can anyone solve this? Ideally the sets of data that don't have a key/value for "colour" won't have {"colour": null} but just won't have the key "colour" at all

I'm on postgres 9.6

1 Answer 1

1

Here is one option that works by unnesting the json array and reaggregating it into one object:

select x.new_js_col
from mytable t
cross join lateral (
    select jsonb_object_agg(obj ->> 'animal', to_jsonb(obj)) new_js_col
    from jsonb_array_elements(t.js_col) as x(obj)
) x(new_js_col)

This assumes that you have a jsonb column called js_col in table mytable.

Demo on DB Fiddle:

| new_js_col                                                                                             |
| :----------------------------------------------------------------------------------------------------- |
| {"cat": {"type": "pet", "animal": "cat"}, "cow": {"type": "farm", "animal": "cow", "colour": "brown"}} |
Sign up to request clarification or add additional context in comments.

Comments

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.