0

This is the current code I'm using.

SELECT
(agent->>0)::jsonb->>'key',
(agent->>1)::jsonb->>'key'
FROM
table;

But it's possible that the jsonb column(agent) contains more than 2 sets of values. Is it possible to write a query without specifying indexing(not including 0,1 in query) and get the result as array_agg using just the key.

Sample jsonb :

[
  {
    "name" : "A",
    "key" : "KA"
  },
  {
    "name" : "B",
    "key" : "KB"
  }
]

My desired output be :

[KA, KB]
2
  • Post a sample of jsonb. Commented Aug 17, 2021 at 11:26
  • Posted a sample of jsonb @SalmanA, thanks. Commented Aug 17, 2021 at 11:32

1 Answer 1

3

With Postgres 12 or later, you can use a JSON path query.

select jsonb_path_query_array(agent, '$.key')
from the_table;
Sign up to request clarification or add additional context in comments.

2 Comments

This works perfectly on my local environment. However when I tried to deploy it for my company, this function wasn't available as the version there is 11.9. Are you aware of any alternative functions I can use for the same, thanks.
I asked a new question here : stackoverflow.com/questions/69033703/…

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.