0

I have table login( id int, meta_skills jsonb), but the jsonb is not stored in key-value pairs.

The data in the jsonb field look like

{
  "Cat1": [
    {
      "Skill_1": 2,
      "Skill_2": 2,
      "Skill_3": 2,
      "Skill_4": 2,
      "Skill_5": 2
    }
  ],
  "Cat2": [
    {
      "Skill_1": 3,
      "Skill_2": 2,
      "Skill_3": 3
    }
  ],
  "Cat3": [
    {
      "Skill_1": 2,
      "Skill_2": 2,
      "Skill_3": 2,
      "Skill_4": 2
    }
  ]
}

The skills values are random values. and I want to prepare the data in following format

enter image description here

2
  • That is not valid JSON. Can you fix the sample? Commented Apr 13, 2021 at 11:49
  • @LaurenzAlbe Removed disturbing comma, some parser don't care, I think. Commented Apr 13, 2021 at 11:58

1 Answer 1

2

You have to unnest the levels:

SELECT login.id,
       u1.category,
       u3.skill,
       u3.level
FROM login
   CROSS JOIN LATERAL jsonb_each(login.meta_skills) AS u1(category,v)
   CROSS JOIN LATERAL jsonb_array_elements(u1.v) AS u2(v)
   CROSS JOIN LATERAL jsonb_each(u2.v) AS u3(skill, level);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. This is absolutely working and first time I have seen the join with JSON functions.

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.