I'm trying to build JSON objects in a loop and store those objects in a JSON array.
I tried to use array_append, json_agg, json_object_agg, but I couldn't get the expected result. Please find the code snippets below.
RETURNS json
as
$$
DECLARE
x text;
obj json;
result json;
y text;
nums json;
BEGIN
FOREACH x IN ARRAY arr
loop
-- doing some id conversion for x
obj = json_build_object('id',x);
result = json_build_array(obj,result);
END LOOP;
return result;
end;
$$
LANGUAGE plpgsql;
The expected output here is :
[
{"id" : "596339663235613739646562"},
{"id" : "506130306666363361633763"},
{"id" : "526362363532646435613438"},
{"id" : "543639333134353433393631"}]
But the actual output I get :
[[[[null, {"id" : "596339663235613739646562"}],
{"id" : "506130306666363361633763"}],
{"id" : "526362363532646435613438"}],
{"id" : "543639333134353433393631"}]
A sample input for function is :
{596339663235613739646562,506130306666363361633763,526362363532646435613438,543639333134353433393631}
Any help is greatly appreciated. Thanks.