0
SELECT * FROM some_table;

I can query to get the following results:

{
    "sku0": {
        "Id": "18418",
        "Desc": "yes"
    },
    "sku1": {
        "Id": "17636",
        "Desc": "no"
    },
    "sku2": {
        "Id": "206714",
        "Desc": "yes"
    },
    "brand": "abc",
    "displayName": "something"
}

First, the number of skus is not fixed. It may be sku0, sku1, sku2, sku3, sku4 ... but they all start with sku.

Then, I want to query Id with 17636 and determine whether its value of Desc is yes or no. After reading the PostgreSQL JSON Functions and Operators documentation, Depressing I didn't find a good way.

I can convert the result into a Python dictionary, and then use python's method can easily achieve my requirements.

If the requirements can also be achieved with postgresql statements, which method is more recommended than the Python dictionary?

3 Answers 3

1

I am not sure I completely understand what the result is you want. But if you want to filter on the Id, you need to unnest all the elements inside the JSON column:

select d.v ->> 'Desc' as description
from the_table t
  cross join jsonb_each(t.data) as d(k,v)
where d.v ->> 'Id' = '17636'
1
  • Bjarni's answer also solved my question, but I think your answer is more general and transplantable. Commented Dec 16, 2019 at 17:50
1

You could use the new jsonpath notation of PostgreSQL v12:

SELECT data @@ '$.* ? (@.Id == "17636").Desc == "yes"'
FROM some_table;

That will start with the root of data ($), find any attribute in it (*), filter only those attributes that contain an Id with value "17636", get their Desc attribute and return TRUE only if that attribute is "yes".

Nice, isn't it?

0

This will probably give you what you need.

select value->>'Desc' from jsonb_each('{
    "sku0": {
        "Id": "18418",
        "Desc": "yes"
    },
    "sku1": {
        "Id": "17636",
        "Desc": "no"
    },
    "sku2": {
        "Id": "206714",
        "Desc": "yes"
    },
    "brand": "abc",
    "displayName": "something"
}'::jsonb)
where key like 'sku%'
and value->>'Id'='17636'

Best regards,
Bjarni

1
  • Your answer also inspired me, but I think the answer of a_horse_with_no_name is more general and portable Commented Dec 16, 2019 at 17:53

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.