Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Postgres select value by key from json in a list

Given the following:

create table test (
  id int, 
  status text
);

insert into test values 
(1,'[]'),
(2,'[{"A":"d","B":"c"}]'),
(3,'[{"A":"g","B":"f"}]');

Is it possible to return?

id  A     B
1   null  null    
2   d     c
3   g     f

I am attempting something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

select id, 
       status::json ->> 0 @> "A" from test

>Solution :

Try this to address your specific example :

SELECT id, (status :: json)#>>'{0,A}' AS A, (status :: json)#>>'{0,B}' AS B
FROM test

see the result

see the manual :

jsonb #>> text[] → text

Extracts JSON sub-object at the specified path as text.

‘{"a": {"b": ["foo","bar"]}}’::json #>> ‘{a,b,1}’ → bar

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading