1

I am working on a PostgreSQL 11 table with a column of nested and multiple jsonb objects

to simulate the issue: -

CREATE TABLE public.test
(
  id integer NOT NULL DEFAULT nextval('test_id_seq'::regclass),
  testcol jsonb
)
insert into test (testcol) values 
('[{"type": {"value": 1, "displayName": "flag1"}, "value": "10"},
{"type": {"value": 2, "displayName": "flag2"}, "value": "20"}, 
{"type": {"value": 3, "displayName": "flag3"}, "value": "30"},
 {"type": {"value": 4, "displayName": "flag4"}},
 {"type": {"value": 4, "displayName": "flag4"}},
 {"type": {"value": 6, "displayName": "flag6"}, "value": "40"}]');

I am trying to:

  1. get outer value if type= specific value. e.g. get the value 30, if flag3 is in displayname.
  2. count occurrence of flag4 in inner json
1
  • because there are two "value" elements, it is not quite clear to me what you are expecting. please add the expected result Commented Oct 9, 2019 at 15:07

1 Answer 1

1

You could use json_to_recordset to parse it:

WITH cte AS (
  SELECT  test.id, sub."type"->'value' AS t_value, sub."type"->'displayName' AS t_name, value
  FROM test
  ,LATERAL jsonb_to_recordset(testcol) sub("type" jsonb, "value" int)
)
SELECT *
FROM cte
-- WHERE ...
-- GROUP BY ...;

db<>fiddle demo

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

5 Comments

hi, i tried with command - 'WITH cte AS ( SELECT test.id, sub."type"->'value' AS t_value, sub."type"->'displayName' AS t_name, value FROM test ,LATERAL json_to_recordset(testcol::json) sub("type" jsonb, "value" text) ) SELECT t_name, value FROM cte where t_name::text='flag3';' but it didnt manage to get flag3, which part i did wrong?
Don't cast to json, use jsonb_to_recordset straight away
it works thanks. but another question, because i have to work with a lot of rows (a row with a jsonb column with 1 to many objects), will this method cause performance issue?
@desmond It depends on too many things. Normally we should treat data in columns as atomic. If this solution starts perfroming badly you could index/normalize data.

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.