I need to convert a text[]
array not starting from index 1 to json, preserving its indexes.
For example, I have text[]
array which starts from index 5:
select myarr from tbl;
myarr
-------------------
[5:5]={blablabla}
If I use array_to_json()
function I get:
select array_to_json(myarr) from tbl;
array_to_json
---------------
["blablabla"]
Information about array index has been lost. But I need it.
I need to get it in correct view (for json) which is:
[null, null, null, null, "blablabla"]
PS, I wrapped the given solution in a function:
CREATE OR REPLACE FUNCTION array_to_json_with_null(myarr text[])
RETURNS json AS
$func$
BEGIN
if myarr is null or cardinality(myarr) = 0 then
return null;
else
return array_to_json (array_fill(null::text,
ARRAY[array_lower(myarr, 1) - 1], ARRAY[1]) || myarr);
end if;
END
$func$ LANGUAGE plpgsql;