2

In PostgreSQL database I have a json column called json. Data inside look like below:

{
    "Version": "0.0.0.1",
    "Items": [
        {
            "Id": "40000000-0000-0000-0000-000000141146",
            "Name": "apple",
            "Score": 64,
            "Value": 1430000
        },
        {
            "Id": "40000000-0000-0000-0000-000000141147",
            "Name": "grapefruit",
            "Score": 58,
            "Value": 1190000
        },
        {
            "Id": "40000000-0000-0000-0000-000000141148",
            "Name": "mango",
            "Score": 41,
            "Value": 170000
        }
    ]
}

What I would like to do is retrieving all Score data from Items elements.

I was trying to use SQL code:

select
substring(json ->> 'Items' from '"Score": (\d*),') as score
from vegetables;

However that returns just the score from first element instead of 3. I was trying to use '\g' flag which supposed to find all results globally, but the code was not working.

Could anyone advise how to do that properly? Thanks in advance!

1
  • Welcome to SO. you should add the desired output also. Commented Nov 13, 2020 at 17:00

1 Answer 1

1

Considering that the data type of json field is jsonb then no need to use substring or regex, simply lateral join with jsonb_array_elements will do the required things for you. Try below query.

select x->>'Score' "Score" from vegetables 
cross join lateral jsonb_array_elements(json->'Items') x

DEMO

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.