Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to compute a JSON field from other fields

Given a table containing the following fields

id sign1 value1 qty1 sign2 value2 qty2
1 "positive" "A" 10 "negative" "B" 5

How to create a SQL query that will generate a JSON object that will look like this?

{"A": 10, "B": -5}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A quick and dirty example:

create table json_object (id integer, sign1 varchar,  value1 varchar, qty1 integer, sign2 varchar,  value2 varchar,  qty2 integer);

insert into json_object values (1, 'positive', 'A', 10, 'negative', 'B', 5);

select json_build_object(value1, qty1 * (case when sign1 = 'positive' then 1 else -1 end), value2, qty2 * (case when sign2 = 'positive' then 1 else -1 end)) from json_object;

 json_build_object   
----------------------
 {"A" : 10, "B" : -5}


Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading