我需要编写一个函数,将json作为输入参数并返回json。
输入json:
[{"id":1,"name":"a"},{"id":2,"name":"b"}]
输出json:
{ "success":[{"id":1,"name":"a"}],"failed":[{"id":2,"name":"b"}]}
循环输入数组,处理(某些逻辑)并返回包含成功和失败数组项的响应。
最佳答案
select json_build_object(
'success', json_agg(col1) filter (where col1->>'name' <> 'a'),
'failure', json_agg(col1) filter (where col1->>'name' = 'a'))
from json_array_elements('[{"id":1,"name":"a"},{"id":2,"name":"b"}]'::json) as t(col1)
印刷品:
{"success" : [{"id":2,"name":"b"}], "failure" : [{"id":1,"name":"a"}]}
Example at SQL Fiddle.