I'm unable to loop multiple array and construct it into jsonb.
CREATE TABLE emr.azt_macres (
id serial NOT NULL,
analyzer_test_full_desc varchar(50) NULL,
specimen_id varchar(100) NULL,
data_reading varchar(20) NULL,
data_result varchar(20) NULL,
result_status varchar(20) NULL,
analyzer_message text NULL,
test_result jsonb NULL,
CONSTRAINT azt_macres_pkey PRIMARY KEY (id)
);
The array look like this. Bare in mind there are two Sample in array which is Sample123 and Sample456
1H|*^&|||Mindry^^|||||||PR|1394-97|20210225142532
P|3||QC1||^^||^^|U||||||||||||||||||||||||||
O|3|1^Sample123^1||TBILV^Bilirubin Total (VOX Method)^^
R|23|KA^Bilirubin Total (VOX Method)^^F|17.648074^^^^|µmol/L|
R|24|ATU^Alanine Aminotransferase^^F|58.934098^^^^|U/L|
L|1|N
1H|*^&|||Mindry^^|||||||PR|1394-97|20210225142532
P|3||QC1||^^||^^|U||||||||||||||||||||||||||
O|3|1^Sample456^1||TBILV^Bilirubin Total (VOX Method)
R|23|TBILV^Bilirubin Total (VOX Method)^^F|17.648074^^^^|
R|24|ALT^Alanine Aminotransferase^^F|58.934098^^^^|U/L|
R|25|TTU^Alkaline phosphatase^^F|92.675340^^^^|U/L|^|N||
I'm able to insert if there are only 1 sample barcode, however the second sample_id is not insert. Do I need to loop the array again?
my code:
CREATE OR REPLACE FUNCTION emr.azintin(v_msgar)
RETURNS jsonb
LANGUAGE plpgsql
AS $function$
DECLARE
v_cnt INT = 0;
v_msgar text[];
v_msgln text;
v_msgtyp character varying(3);
v_tmp text;
macres azt_macres%rowtype;
BEGIN
macres.analyzer_test_full_desc := 'CHEMO';
SELECT split_part(items[3], '^', 2)
INTO macres.specimen_id
FROM (
SELECT string_to_array(element, '|') as items
FROM unnest(v_msgar) as t(element)) t
WHERE items[1] = 'O';
SELECT jsonb_agg(jsonb_build_object('resultId', split_part(items[3],'^',1),'resultValue',split_part(items[4],'^',1)))
INTO macres.test_result
FROM (
SELECT string_to_array(element, '|') as items
FROM unnest(v_msgar) as t(element)) t
WHERE items[1] = 'R';
v_cnt := v_cnt + 1;
BEGIN
INSERT INTO azt_macres(analyzer_test_full_desc, specimen_id, data_reading ,
data_result,result_status,analyzer_message,test_result)
VALUES (macres.analyzer_test_full_desc, macres.specimen_id,macres.data_reading,
macres.data_result,macres.result_status,macres.analyzer_message, macres.test_result);
END;
END
$function$
;
Currently my output is like this
specimen_id | test_result |
---|---|
sample123 | [{"resultId": "KA", "resultValue": "17.648074"}, {"resultId": "ATU", "resultValue":"58.934098"}, {"resultId": "TBILV", "resultValue": "17.648074"}, {"resultId": "ALT","resultValue": "58.934098"}, {"resultId": "TTU", "resultValue": "92.675340"}] |
supposely my output should be like this
specimen_id | test_result |
---|---|
sample123 | [{"resultId": "KA", "resultValue": "17.648074"}, {"resultId": "ATU","resultValue":"58.934098"}] |
sample456 | [{"resultId": "TBILV", "resultValue": "17.648074"}, {"resultId": "ALT","resultValue": "58.934098"}, {"resultId": "TTU", "resultValue": "92.675340"}] |