I am using json_build_object
to build a json object using other columns:
json_build_object(value1, qty1, value2, qty2, value3, qty3)
Every pair (value, qty)
go together.
I only want the json object to contain the pairs that don’t have an empty value.
At the moment, each pair in json_build_object
is hardcoded. How can I change that?
I have this so far:
create table json_object (id integer, value1 varchar, qty1 integer, value2 varchar, qty2 integer, value3 varchar, qty3 integer);
insert into json_object values (1, 'A', 10, '', 0, '', 0);
insert into json_object values (2, 'A', 10, 'B', 5, 'C', 10);
insert into json_object values (3, 'A', 10, 'B', 5, '', 0);
select json_build_object(value1, qty1, value2, qty2, value3, qty3) from json_object;
json_build_object
----------------------
{"A" : 10, "" : 0, "" : 0}
{"A" : 10, "B" : 5, "C" : 10}
{"A" : 10, "B" : 5, "" : 0}
but I want the output to be:
{"A" : 10}
{"A" : 10, "B" : 5, "C" : 10}
{"A" : 10, "B" : 5}
2
Answers
fiddle
fiddle
This will work so long as the column names follow a regular convention:
Working fiddle