如何在PostgreSQL 9.3中循环遍历JSON数组

51

我正在为一个新的PostgreSQL数据库编写函数,并且尝试循环遍历嵌套结构。

使用新的JSON函数是否可能实现这一点?下面是我尝试做的:

I'm writing function for a new postgreSQL db and i'm trying to loop over a nested structure.

Is that even possible with the new JSON functions? What i'm trying to do is here below:

DO
$BODY$
DECLARE
    omgjson json := '[{ "type": false }, { "type": "photo" }, {"type": "comment" }]';
    i record;
BEGIN
  FOR i IN SELECT * FROM json_array_elements(omgjson)
  LOOP
    RAISE NOTICE 'output from space %', i;
  END LOOP;
END;
$BODY$ language plpgsql

这将返回一组记录(文本!),而不是JSON!,所以我无法像i->>'type'那样查询它,但这正是我想要实现的...

1个回答

98

我有点儿傻,但是PostgreSQL网站上关于json功能的文档实际上非常少。

解决这个问题,我所做的就是:

DO
$BODY$
DECLARE
    omgjson json := '[{ "type": false }, { "type": "photo" }, {"type": "comment" }]';
    i json;
BEGIN
  FOR i IN SELECT * FROM json_array_elements(omgjson)
  LOOP
    RAISE NOTICE 'output from space %', i->>'type';
  END LOOP;
END;
$BODY$ language plpgsql

10
在较新版本的PostgreSQL中,您可以使用jsonb_array_elements函数。 - Doctor Eval

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接