[英]How to ADD and REMOVE in a new json-array element in PostgreSQL V9.4
I`m making a loop to create a new json matrix with only certain elements, for this I need to go through the previously created json-array and PUSH (ADD ELEMENT) and POP (REMOVE ELEMENT) the elements according to the condition.我正在创建一个循环来创建一个新的 json 矩阵,其中只有某些元素,为此我需要通过先前创建的 json-array 和 PUSH(添加元素)和 POP(删除元素)元素来 go 条件。
I receive something like that我收到类似的东西
[
{"id":1 , "data": "test_a"},
{"id":2 , "data": "test_t"},
{"id":3 , "data": "test_h"},
.....
]
and I`m doing something like this to the loop我正在对循环做这样的事情
DECLARE
_test json;
i json;
_new_jsn json;
BEGIN
_test := SELECT json_agg(json_build_object('id', 1, 'data', 'test'))
FOR i IN SELECT * FROM json_array_elements(_test) LOOP
RAISE NOTICE 'element %',i;
END LOOP;
From here, I don't know how to continue to make to ADD and REMOVE element in a new param.从这里开始,我不知道如何继续在新参数中添加和删除元素。
My filter is based in an IF-ELSE so if I have我的过滤器基于 IF-ELSE 所以如果我有
FOR i IN SELECT * FROM json_array_elements(_test) LOOP
IF i->>id > 2 THEN
..... Add the element in _new_jsn
ELSE
.... Remove/Ignore the element
END IF;
END LOOP;
I want to receive after the loop something like this我想在循环后收到这样的东西
[
{"id":3 , "data": "test_h"},
{"id":4 , "data": "test_c"},
.....
]
I believe you are looking for我相信你正在寻找
DECLARE
test CONSTANT json := json_build_array(
json_build_object('id', 1, 'data', 'test_a'),
json_build_object('id', 2, 'data', 'test_t'),
json_build_object('id', 3, 'data', 'test_h'),
json_build_object('id', 4, 'data', 'test_c')
);
result json;
BEGIN
result := (SELECT json_agg(el)
FROM json_array_elements(test) AS t(el)
WHERE (el->>'id')::int > 2);
-- …
END;
You don't need any loop or IF
statements here.您在这里不需要任何循环或IF
语句。 Just a SELECT
query with a WHERE
clause.只是一个带有WHERE
子句的SELECT
查询。
Online demo (I haven't found a better way to print the result than to raise an exception:-/) 在线演示(我没有找到比引发异常更好的打印结果的方法:-/)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.