Postgres:在SQL中循环遍历json数组吗?

时间:2017-07-22 19:38:42

标签: sql json postgresql

我使用的是postgres 9.6.3,需要将以下python代码转换为sql查询:

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'])

该表有两列:( membershipid整数主键,数据jsonb)。我不知道如何在sql中处理这样的数组。该数组是可变长度的,可能包含也可能不包含activityHash ==所需值的条目。

查询所需的结果类似于SELECT membership,清除FROM表。

2 个答案:

答案 0 :(得分:1)

我一直在寻找jsonb_array_elements(活动)

答案 1 :(得分:0)

我建议您查看此link,它将指导您如何在Postgres中遍历JSONB。

尝试以下查询,看看它是否适合您:

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;