简体   繁体   English

如何在postgres查询中解析json数组

[英]How to parse json array in postgres query

I need to parse json array from below table column. 我需要解析表格列下面的json数组。 The result should be answer of Q2 question in below example. 结果应该是以下例子中Q2问题的答案。

id      data
1   [{"questionId":"Q1","answer":"A1"},{"questionId":"Q2","answer":"A2"}]
2   [{"questionId":"Q1","answer":"A1"},{"questionId":"Q2","answer":"A2"}]

So the result should be like this 所以结果应该是这样的

1 A2
2 A2

I tried with data::json->'answer' as answer but doesn't seem to work on array 我尝试使用data::json->'answer' as answer但似乎不适用于数组

You may use json_array_elements and filter rows using a WHERE clause 您可以使用json_array_elements并使用WHERE子句过滤行

select id, j->>'answer' as answer FROM t 
cross join lateral json_array_elements(data::json) as j
WHERE j->>'questionId' = 'Q2'

Demo 演示

Try the ># operator . 试试>#运算符

create temporary table t (id serial primary key, data json);
insert into t (
  data
)
values (
  '[{"questionId":"Q1","answer":"A1"},{"questionId":"Q2","answer":"A2"}]'
);
insert into t (
  data
)
values (
  '[{"questionId":"Q1","answer":"A1"},{"questionId":"Q2","answer":"A2"}]'
);

-- The Q1 ist the 2nd element in the array and has index 1.
select id, data::json#>'{1,answer}' from t;

Output: 输出:

+------+------------+
| id   | ?column?   |
|------+------------|
| 1    | "A2"       |
| 2    | "A2"       |
+------+------------+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM