1

I am using postgres 9.6.3 and need to convert the following python code to a sql query:

data = response.json()
activities = data['Response']['data']['activities']
for activity in activities:
    activityHash = int(activity['activityHash'])
    if activityHash == 2659248071:
        clears = int(activity['values']['activityCompletions']['basic']['value'])

The table has two columns: (membershipid integer primary key, data jsonb). I am not sure how to handle an array like this in sql. The array is variable length and might or might not include an entry where activityHash == the desired value.

The desired result from the query would be something like SELECT membershipid, clears FROM table.

3
  • What do you actually want it to do? Do you have any SQL to start with? Commented Jul 22, 2017 at 19:41
  • Aside of the SQL equivalent, do you know about PL/Python? Commented Jul 22, 2017 at 19:54
  • edit your question and add some sample data and the expected output based on that data. Formatted text please, no screen shots. Do not post code or additional information in comments Commented Jul 22, 2017 at 20:18

2 Answers 2

2

I was looking for jsonb_array_elements(activities)

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

Comments

0

I recommend you check out this link that walks you through how to traverse JSONB in Postgres.

Try the following query and see if that works for you:

SELECT
membershipid,
'data' -> 'activity' -> 'response' -> 'data' -> 'activities' ->> 'activityHash' AS activityHash,
'data' -> 'activity' -> 'response' -> 'data' -> 'activities' -> 'activityHash' -> 'values' -> 'activityCompletions' -> 'basic' ->> 'value' AS clears

FROM yourtablename

WHERE
('data' -> 'activity' -> 'response' -> 'data' -> 'activities' ->> 'activityHash')::int = 2659248071;

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.