1

Suppose that I have some PostgreSQL table ('table_1') that I want to select from in a Python script. This table has a column with JSON data (called 'json_data') like the following, e.g.:

{'4369': 2, '8465': 1, '12561': 1, '12562': 1}

Now I have a list in Python that looks the following:

[4369, 8465, 12561, 16657]

And my goal is to return a JSON/dict from the postgresql table that only contains key/value pairs for which the key is in the Python list for each row. For the above, I would thus expect a JSON returned as:

{'4369': 2, '8465': 1, '12561': 1}

My guess is that it has to look somewhat like this, but I have no clue what has to go at the '...'

SELECT json_data ->> ... IN 'python_list'
FROM table_1

2 Answers 2

2

You can use JSONB_OBJECT_AGG(), JSONB_EACH() and JSONB_ARRAY_ELEMENTS() function together within a SELECT Statement which includes JOINs in order to match elements of the dict object with the keys of JSON object such as

SELECT JSONB_OBJECT_AGG( j1.key, j1.value ) AS js_data
  FROM table_1 t
 CROSS JOIN JSONB_EACH(json_data) AS j1 
  JOIN JSONB_ARRAY_ELEMENTS('[4369, 8465, 12561, 16657]'::JSONB) AS j2
    ON j2.value::INT = j1.key::INT

Demo

P.S: I've preferred JSONB, which stores data in a decomposed binary form and faster to process , data type. For JSON, check out the following

Demo2

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

3 Comments

JSONB makes imho only sense when you need indexes on this data as well, for faster searching. Otherwise it takes more storage space and is slower on INSERT's. I don't think our examples can use an index.
you're right @FrankHeikens , that will depend on the OP'S choice.
With some tweaking, this gets me where I have to be. Both good answers though :)
1

Example, just in plain SQL and using a CTE to mimic your table:

WITH i AS (
    SELECT  '{"4369": 2, "8465": 1, "12561": 1, "12562": 1}'::json AS json_data
)
SELECT  *
FROM    i, -- your table name
        json_each(json_data)
WHERE   key::int =any(ARRAY[4369, 8465, 12561, 16657]);

The function json_each (or jsonb_each when using jsonb data type) does the trick.

I hope you can transform this into something useful in python.

2 Comments

OP clearly states that the expected result is of the form {'4369': 2, '8465': 1, '12561': 1}
@BarbarosÖzhan: You're right, forgot that part

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.