Get nested JSON values in PL/SQL - json

I am trying to get nested field's values from json which is returned by function apex_web_service.make_rest_request.
DECLARE
v_address_json clob;
v_address_response clob;
l_object_address json_object_t;
BEGIN
SELECT
json_object ('Addresses' value json_object(
'AddName' value ('HQ') ,
'AddLine1' value tab1.ADDRESS_LINE1 ,
.
.
.
.
into
v_address_json
FROM
tab1 t1,
tab2 t2
WHERE
.....
.....;
v_address_response := apex_web_service.make_rest_request
(
p_url => 'https://...../addresses',
p_http_method => 'POST',
p_body => v_address_json
);
DBMS_OUTPUT.PUT_LINE('v_address_response : '||v_address_response);
At this point I am getting below in v_address_response.
{
"Metadata" : {
"application" : "",
"applicationRefId" : ""
},
"APIResponse" : {
"Status" : "SUCCESS",
"Error" : {
"Code" : "",
"Message" : "",
"Detail" : ""
}
},
"ven" : {
"Id" : 12345,
"Addresses" : [ {
"vAddId" : 1122334455,
"vAddName" : "HQ",
"AddLine1" : "1/A2, ABC, XYZ ROAD, IN",
"City" : "JKL",
"State" : "AB",
"PCode" : "102030",
"Country" : "IN",
"TaxReg" : [ {
"RegId" : 998877,
"EffectiveFrom" : "2029-11-13"
} ],
"TaxRep" : [ {
"TaxRepId" : 665544,
"EffectiveFrom" : "2022-01-01"
} ]
} ]
}
}
further I am trying to get field's value as below.
l_object_address := json_object_t.parse(v_address_response);
if l_object_address.get_Object('APIResponse').get_string('Status') = 'SUCCESS'
then
DBMS_OUTPUT.PUT_LINE(' New Address ID : '||l_object_address.get_Object('Addresses').get_string('vAddId')); --output xx
else
DBMS_OUTPUT.PUT_LINE('Error in creating address');
end if;
exception when others then
null;
end;
in the above section I am able to get value for APIResponse--> Status i.e 'SUCCESS' but unable to get value of vAddId, RegId and other nested fields. At comment, output xx, nothing is getting printed.

If you're just after reading values out of the JSON (and not intend to traverse the "object tree" up and down") I would use the JSON_TABLE SQL Function, as follows:
BEGIN
for i in (
select status,
vAddId,
vAddName,
RegId,
EffectiveFrom
-- , other columns go here
from json_table(
v_address_response,
'$'
columns(
status varchar2(255) path '$.APIResponse.Status',
-- other columns on this level go here
ven_id number path '$.ven.Id',
nested path '$.ven.Addresses' columns(
vAddId number path '$.vAddId',
vAddName varchar2(255) path '$.vAddName',
-- other columns on this level go here
nested path '$.TaxReg' columns(
RegId number path '$.RegId',
EffectiveFrom varchar2(255) path '$.EffectiveFrom'
)
)
)
)
)
loop
-- process the data here
if i.status = 'SUCCESS' then
DBMS_OUTPUT.PUT_LINE(' New Address ID : '|| i.vAddId);
else
DBMS_OUTPUT.PUT_LINE('Error in creating address');
end if;
end loop;
end;
/
fiddle

You need to descend into the ven object first and then Addresses is an array of objects, and not an object, so you need to find the zero-indexed element of the array and then get the attribute of the object. To do that, you can use:
DECLARE
v_address_response CLOB := '{
"Metadata" : {
"application" : "",
"applicationRefId" : ""
},
"APIResponse" : {
"Status" : "SUCCESS",
"Error" : {
"Code" : "",
"Message" : "",
"Detail" : ""
}
},
"ven" : {
"Id" : 12345,
"Addresses" : [ {
"vAddId" : 1122334455,
"vAddName" : "HQ",
"AddLine1" : "1/A2, ABC, XYZ ROAD, IN",
"City" : "JKL",
"State" : "AB",
"PCode" : "102030",
"Country" : "IN",
"TaxReg" : [ {
"RegId" : 998877,
"EffectiveFrom" : "2029-11-13"
} ],
"TaxRep" : [ {
"TaxRepId" : 665544,
"EffectiveFrom" : "2022-01-01"
} ]
} ]
}
}';
l_object JSON_OBJECT_T;
l_address JSON_OBJECT_T;
BEGIN
l_object := json_object_t.parse(v_address_response);
if l_object.get_Object('APIResponse').get_string('Status') = 'SUCCESS' then
l_address := TREAT( l_object.get_Object('ven').get_Array('Addresses').get(0) AS JSON_OBJECT_T );
DBMS_OUTPUT.PUT_LINE(' New Address ID : '||l_address.get_Number('vAddId')); --output xx
else
DBMS_OUTPUT.PUT_LINE('Error in creating address');
end if;
end;
/
Which outputs:
New Address ID : 1122334455
fiddle

Related

Delete value from nested json - postgres

I have the json block modeled below. I want to selectively delete individual blocks from my_items based on the id which is AAA and BBB in my sample. ie if I tried to delete the AAA block under my_items I would want tojust delete the {"id" : "AAA"} but if wanted to delete the BBB block it would delete the larger {"name" : "TestRZ", "id" : "BBB", "description" : ""} block.
I know I can use the #- to remove whole blocks like SELECT '{sample_json}'::jsonb #- '{my_items}' would purge out the whole my_items block. But I dont know how to use this to conditionally delete children under a parent block of json. I have also used code similar to this example to append data inside a nested structure by reading in the node of the nested structure cat-ing new data to it and rewriting it. UPDATE data SET value= jsonb_set(value, '{my_items}', value->'items' || (:'json_to_adds'), true) where id='testnofeed'.
But I dont know how to apply either of these methods to: 1)Delete data in nested structure using #- or 2)Do the same using `jsonb_set. Anyone have any guidance for how to do this using either of these(or another method).
{
"urlName" : "testurl",
"countryside" : "",
"description" : "",
"my_items" : [
{
"id" : "AAA"
},
{
"name" : "TestRZ",
"id" : "BBB",
"description" : ""
},
],
"name" : "TheName"
}
Data is stored in value jsonb. when I update I will be able to pass in a unique kind so that it only updates this json in one row in db.
-- Table Definition
CREATE TABLE "public"."data" (
"id" varchar(100) NOT NULL,
"kind" varchar(100) NOT NULL,
"revision" int4 NOT NULL,
"value" jsonb
);
This works in PostgreSQL 12 and later with jsonpath support. If you do not have jsonpath, then please leave a comment.
with data as (
select '{
"urlName" : "testurl",
"countryside" : "",
"description" : "",
"my_items" : [
{
"id" : "AAA"
},
{
"name" : "TestRZ",
"id" : "BBB",
"description" : ""
}
],
"name" : "TheName"
}'::jsonb as stuff
)
select jsonb_set(stuff, '{my_items}',
jsonb_path_query_array(stuff->'my_items', '$ ? (#."id" <> "AAA")'))
from data;
jsonb_set
---------------------------------------------------------------------------------------------------------------------------------------------------
{"name": "TheName", "urlName": "testurl", "my_items": [{"id": "BBB", "name": "TestRZ", "description": ""}], "countryside": "", "description": ""}
(1 row)
To update the table directly, the statement would be:
update data
set value = jsonb_set(value, '{my_items}',
jsonb_path_query_array(value->'my_items',
'$ ? (#."id" <> "AAA")'));
This works for versions before PostgreSQL 12:
with data as (
select 1 as id, '{
"urlName" : "testurl",
"countryside" : "",
"description" : "",
"my_items" : [
{
"id" : "AAA"
},
{
"name" : "TestRZ",
"id" : "BBB",
"description" : ""
}
],
"name" : "TheName"
}'::jsonb as stuff
), expand as (
select d.id, d.stuff, e.item, e.rn
from data d
cross join lateral jsonb_array_elements(stuff->'my_items') with ordinality as e(item, rn)
)
select id, jsonb_set(stuff, '{my_items}', jsonb_agg(item order by rn)) as new_stuff
from expand
where item->>'id' != 'AAA'
group by id, stuff;
id | new_stuff
----+---------------------------------------------------------------------------------------------------------------------------------------------------
1 | {"name": "TheName", "urlName": "testurl", "my_items": [{"id": "BBB", "name": "TestRZ", "description": ""}], "countryside": "", "description": ""}
(1 row)
The direct update for this is a little more involved:
with expand as (
select d.id, d.value, e.item, e.rn
from data d
cross join lateral jsonb_array_elements(value->'my_items')
with ordinality as e(item, rn)
), agg as (
select id, jsonb_set(value, '{my_items}', jsonb_agg(item order by rn)) as new_value
from expand
where item->>'id' != 'AAA'
group by id, value
)
update data
set value = agg.new_value
from agg
where agg.id = data.id;

How to remove null attributes from my JSON in MySQL

I am having a table which is storing the JSON values. Within these JSONs, the JSON is having null attributes like below :
{
"name" : "AAAA",
"department" : "BBBB",
"countryCode" : null,
"languageCode" : null,
"region" : "AP"
}
I would like to write a query so that all the null attributes are removed from the output. For e.g. for the above-mentioned JSON, the resultant output JSON should be like this.
{
"name" : "AAAA",
"department" : "BBBB",
"region" : "AP"
}
I would like to have a generic query which I can apply to any JSON to get rid of null attributes in MySQL (v5.7).
In case you don't know all the keys in advance:
WITH j AS (SELECT CAST('{"a": 1, "b": "null", "c": null}' AS JSON) o)
SELECT j.o, (SELECT JSON_OBJECTAGG(k, JSON_EXTRACT(j.o, CONCAT('$."', jt.k, '"')))
FROM JSON_TABLE(JSON_KEYS(o), '$[*]' COLUMNS (k VARCHAR(200) PATH '$')) jt
WHERE JSON_EXTRACT(j.o, CONCAT('$."', jt.k, '"')) != CAST('null' AS JSON)) removed
FROM j;
Outputs:
o
removed
{"a": 1, "b": "null", "c": null}
{"a": 1, "b": "null"}
And this will keep your keys with string value "null", which is different from json null.
The following query will work for removing a single key value pair, where the value is NULL:
SELECT JSON_REMOVE(col, '$.countryCode')
FROM yourTable
WHERE CAST(col->"$.countryCode" AS CHAR(50)) = 'null';
But, I don't see a clean way of doing multiple removals in a single update. We could try to chain the updates together, but that would be ugly and non readable.
Also, to check for your JSON null, I had to cast the value to text first.
Demo
How you can remove null keys using JSON_REMOVE function. $.dummy is used if the condition is false.
select json_remove(abc,
case when json_unquote(abc->'$.name') = 'null' then '$.name' else '$.dummy' end,
case when json_unquote(abc->'$.department') = 'null' then '$.department' else '$.dummy' end,
case when json_unquote(abc->'$.countryCode') = 'null' then '$.countryCode' else '$.dummy' end,
case when json_unquote(abc->'$.languageCode') = 'null' then '$.languageCode' else '$.dummy' end,
case when json_unquote(abc->'$.region') = 'null' then '$.region' else '$.dummy' end)
from (
select cast('{
"name" : "AAAA",
"department" : "BBBB",
"countryCode" : null,
"languageCode" : null,
"region" : "AP"
}' as json) as abc ) a
Output:
{"name": "AAAA", "region": "AP", "department": "BBBB"}

Parsing JSON in Postgres

I have the following JSON that I'd like to parse inside a postgresql function.
{
"people": [
{
"person_name": "Person#1",
"jobs": [
{
"job_title": "Job#1"
},
{
"job_name": "Job#2"
}
]
}
]
}
I need to know how to pull out the person_name, and then loop thru the jobs and pull out the job_title. This is as far as I've been able to get.
select ('{"people":[{"person_name":"Person#1","jobs":[{"job_title":"Job#1"},
{"job_name":"Job#2"}]}]}')::json -> 'people';
https://www.db-fiddle.com/f/vcgya7WtVdvj8q5ck5TqgX/0
Assuming that job_name in your post should be job_title. I expanded your test data to:
{
"people": [{
"person_name": "Person#1",
"jobs": [{
"job_title": "Job#11"
},
{
"job_title": "Job#12"
}]
},
{
"person_name": "Person#2",
"jobs": [{
"job_title": "Job#21"
},
{
"job_title": "Job#22"
},
{
"job_title": "Job#23"
}]
}]
}
Query:
SELECT
person -> 'person_name' as person_name, -- B
json_array_elements(person -> 'jobs') -> 'job_title' as job_title -- C
FROM (
SELECT
json_array_elements(json_data -> 'people') as person -- A
FROM (
SELECT (
'{"people":[ '
|| '{"person_name":"Person#1","jobs":[{"job_title":"Job#11"}, {"job_title":"Job#12"}]}, '
|| '{"person_name":"Person#2","jobs":[{"job_title":"Job#21"}, {"job_title":"Job#22"}, {"job_title":"Job#23"}]} '
|| ']}'
)::json as json_data
)s
)s
A Getting person array; json_array_elements expands all array elements into one row per element
B Getting person_name from array elements
C Expanding the job array elements into one row per element and getting the job_title
Result:
person_name job_title
----------- ---------
"Person#1" "Job#11"
"Person#1" "Job#12"
"Person#2" "Job#21"
"Person#2" "Job#22"
"Person#2" "Job#23"

Postgres + Sequelize: How to read function result?

I have a function payment_summary() as below:
CREATE OR REPLACE FUNCTION payment_summary()
RETURNS SETOF PAYMENT_SUMMARY_TYPE
LANGUAGE plpgsql
AS $$
DECLARE
payment_sum payment_summary_type%ROWTYPE;
BEGIN
FOR payment_sum IN SELECT
pay.application_no,
project.title,
pay.payment_rec,
customer.cust_name,
project.estimated_cost,
(project.estimated_cost - pay.payment_rec) AS outstanding_amt
FROM project
INNER JOIN customer
ON project.customer_cust_id = customer.cust_id
INNER JOIN
(SELECT
project.application_no,
sum(payment.amount) AS payment_rec
FROM payment
INNER JOIN project
ON payment.project_id = project.project_id
WHERE payment.drcr_flg = 'Cr'
GROUP BY project.application_no) AS pay
ON pay.application_no = project.application_no
LOOP
RETURN NEXT payment_sum;
END LOOP;
END;
$$;
PAYMENT_SUMMARY_TYPE is defined as:
CREATE TYPE PAYMENT_SUMMARY_TYPE AS
(
application_no VARCHAR(150),
title VARCHAR(500),
payment_rec INTEGER,
customer_name VARCHAR(500),
estimated_cost INTEGER,
outstanding_amt INTEGER
);
Using below code to execute the function and get results:
sequelize.query('SELECT payment_summary()').then(function(data) {
res.json(data);
});
Getting below as response:
[
[
{
"payment_summary": "(716,\"C1\",100000,\"C1 - city\",0,-100000)"
},
{
"payment_summary": "(716,\"C2\",100000,\"C2 - city\",0,-100000)"
}
],
{
"command": "SELECT",
"rowCount": 2,
"oid": null,
"rows": [
{
"payment_summary": "(716,\"C1\",100000,\"C1 - city\",0,-100000)"
},
{
"payment_summary": "(716,\"C2\",100000,\"C2 - city\",0,-100000)"
}
],
"fields": [
{
"name": "payment_summary",
"tableID": 0,
"columnID": 0,
"dataTypeID": 17453,
"dataTypeSize": -1,
"dataTypeModifier": -1,
"format": "text"
}
],
"_parsers": [
null
],
"rowAsArray": false
}
]
I need the response in below format:
[
{
application_no: 716,
title: "C1",
payment_rec : 100000,
customer_name : "C1 - city"
estimated_cost : 0
outstanding_amt : -100000
},
{
application_no: 717,
title: "C2",
payment_rec : 100000,
customer_name : "C2 - city"
estimated_cost : 0
outstanding_amt : -100000
}
]
How can i read / convert the response in required format ?

Postgres nested JSON array using row_to_json

I am trying to create nested json array using 2 tables.
I have 2 tables journal and journaldetail.
Schema is -
journal : journalid, totalamount
journaldetail : journaldetailid, journalidfk, account, amount
Relation between journal and journaldetail is one-to-many.
I want the output in following format :
{ journalid : 1,
totalamount : 1000,
journaldetails : [
{
journaldetailid : j1,
account : "abc",
amount : 500
},
{
journaldetailid : j2,
account : "def",
amount : 500
}
]}
However, by writing this query as per this post the query is:
select j.*, row_to_json(jd) as journal from journal j
inner join (
select * from journaldetail
) jd on jd.sjournalidfk = j.sjournalid
and the output is like this :
{ journalid : 1,
totalamount : 1000,
journaldetails :
{
journaldetailid : j1,
account : "abc",
amount : 500
}
}
{ journalid : 1,
totalamount : 1000,
journaldetails :
{
journaldetailid : j2,
account : "def",
amount : 500
}
}
I want the child table data as nested array in the parent.
I found the answer from here:
Here is the query :
select row_to_json(t)
from (
select sjournalid,
(
select array_to_json(array_agg(row_to_json(jd)))
from (
select sjournaldetailid, saccountidfk
from btjournaldetail
where j.sjournalid = sjournalidfk
) jd
) as journaldetail
from btjournal j
) as t
This gives output in array format.