0

I need some help in converting JSON array in postgresTO JSON object as below. Please Note the keys are not known in advance, any key can show up in the JSON array. Is there a way to just flatten it out.

INPUT:-

 [{"col1": "1", "col2": null, "col3": "7"}, {"col4": "19"}, {"col5": "19", "col6":"18"}]

OUTPUT:-

{"col1": "1", "col2": null, "col3": "7", "col4": "19", "col5": "19", "col6":"18"}

Thank you

1
  • 1
    Unrelated to your problem, but: Postgres 9.3 and 9.5 are no longer supported you should plan an upgrade as soon as possible. Additionally: the JSON support in modern Postgres versions is way better than it was back then. Commented Sep 15, 2022 at 11:41

1 Answer 1

1

First flatten (using json_array_elements and then json_each on each array element) and then aggregate back with json_object_agg.

select json_object_agg(k, v) 
from json_array_elements
('[
  {"col1":"1","col2":null,"col3":"7"},
  {"col4":"19"},
  {"col5":"19","col6":"18"}
]') as ja 
cross join lateral json_each(ja) as jl(k, v);
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.