1

I have Postgres column of JSONB array of objects, looking like this :

[{"key": "meetingDate", "value": "2022-08-22"}, {"key": "userName", "value": "Testing User"}]

how can i get the result like this

meetingDate userName
2022-08-22 TestingUser
4
  • Does you array always contain only two elements? What if there are 5 usernames but only 3 meeting dates? Commented Sep 30, 2022 at 9:47
  • the array only contains this structure one meeting date and one username Commented Sep 30, 2022 at 9:56
  • Would be a lot easier if it was {"meetingDate": "2022-08-22", "userName": "TestingUser"} Commented Sep 30, 2022 at 10:01
  • but i cant change the structure as the structure i mentioned is required for the business logic Commented Sep 30, 2022 at 10:08

2 Answers 2

3

Use json_array_elements (db fiddle here).

with t(v) as (values
  ('[{"key": "meetingDate", "value": "2022-08-22"}, {"key": "userName", "value": "Testing User"}]'::jsonb)
)
select (select a.e->>'value' from json_array_elements(t.v::json) a(e) where a.e->>'key' = 'meetingDate') as meetingDate
     , (select a.e->>'value' from json_array_elements(t.v::json) a(e) where a.e->>'key' = 'userName') as userName
from t
Sign up to request clarification or add additional context in comments.

Comments

0

You can use a JSON path expression:

select jsonb_path_query_first(the_column, '$[*] ? (@.key == "meetingDate").value') #>> '{}' as meetingdate,
       jsonb_path_query_first(the_column, '$[*] ? (@.key == "userName").value') #>> '{}' as username
from the_table;

jsonb_path_query_first returns a jsonb value, but there is no direct cast from there to text. The #>> '{}' is a small hack to convert the jsonb value to a text value. If you are OK with a jsonb value, you can remove it.

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.