循环访问JSON对象以获取给定属性名称的值

时间:2014-05-16 14:50:10

标签: json postgresql for-loop plpgsql

我有一些JSON对象,我需要为它们获取属性值 我的情况基于这个问题:

DO $$
DECLARE 
v_whatever character varying := 'a';
v_res character varying;
BEGIN
SELECT params->>v_whatever FROM user_info1 WHERE uid = 9 INTO v_res;
RAISE NOTICE 'v_res: %', v_res ;
END; $$

在表格中,列参数(类型为json)的值为:{"a":"b","b":"c","c":"d"}, 查询返回v_res: b

因为我没有特定的属性名称,所以代码如下:

DECLARE
v_temp char varying;
v_obj char varying[];
comp char varying[];
BEGIN
SELECT json_object_keys(params) FROM  user_info1 WHERE uid = p_uid into v_temp;
SELECT params->>v_temp FROM user_info1 WHERE uid = 9 INTO v_obj;

1 个答案:

答案 0 :(得分:0)

一个基本的plpgsql FOR loop

DO
$$
DECLARE 
   v_whatever text := 'a';
   v_res text;
BEGIN

FOR v_res IN
   SELECT params->>v_whatever
   FROM   user_info1
   WHERE  uid = 9
LOOP
   RAISE NOTICE 'v_res: %', v_res;
END LOOP;

END;
$$

请注意,基于集合的方法通常比循环更有效。期待unnest() ..