1

I have a Postgres json field products with jsonb like this

{
  "user": "7871425f-abb4-42c6-8e4d-36c99ec2f67c",
  "product": {
    "ef688ed3-12c9-4e22-af5f-32a7b32db628": {
      "category": "basic"
    },
    "8fbef749-42dd-4a40-a98a-ebe7b54c4388": {
      "category": "advanced"
    },
    "d475185f-d014-4c60-aebd-cecaed7df550": {
    }
  }
}

I am trying to extract category for each product to get something like

"ef688ed3-12c9-4e22-af5f-32a7b32db628": "basic"
"8fbef749-42dd-4a40-a98a-ebe7b54c4388": "advanced"
"d475185f-d014-4c60-aebd-cecaed7df550": NULL

Any help highly appreciated

1 Answer 1

2

jsonb_each() would do the trick:

SELECT  key
    ,       value->>'category'
FROM    jsonb_each('{
  "user": "7871425f-abb4-42c6-8e4d-36c99ec2f67c",
  "product": {
    "ef688ed3-12c9-4e22-af5f-32a7b32db628": {
      "category": "basic"
    },
    "8fbef749-42dd-4a40-a98a-ebe7b54c4388": {
      "category": "advanced"
    },
    "d475185f-d014-4c60-aebd-cecaed7df550": {
    }
  }
}'::jsonb ->'product');

The sort order is up to you.

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

Comments

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.