[英]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
但似乎不适用于数组
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.