0

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:

select id, 
       status::json ->> 0 @> "A" from test
2
  • 1
    The id numbers in your example are off by one. Right? Commented Nov 30, 2021 at 19:39
  • @TimRoberts Yep, thanks. I modified the post. Commented Nov 30, 2021 at 19:41

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

This does it:

SELECT id,
    (status::json->0)->"A" as A,
    (status::json->0)->"B" as B
FROM test;

3 Comments

sqlfiddle.com/#!17/770b1/12... I think I am getting an error.
Interesting; that exact query worked for me with Postgres 9.5.

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.