I am trying to create a nested json object using Oracle SQL. I am able to create JSON objects where the hierarchy level is predefined. In this case, it is dynamic and not able to find SQL or PLSQL solution for this nested data.
I have a table with below data,
I want the output as below using Oracle SQL or PLSQL
{
"data": [
{
"ID": 1,
"NAME": "India",
"child": [
{
"ID": 3,
"NAME": "FINANCE",
"child": [
{
"ID": 5,
"NAME": "HR"
}
]
}
]
},
{
"ID": 2,
"NAME": "Canada",
"child": [
{
"ID": 4,
"NAME": "IT"
}
]
}
]
}
Can anyone help me on this?
2
Answers
You can create a recursive function:
Which, for the sample data:
Then:
Outputs:
fiddle
Without a function: you can make a view of it (the outermost JSON_QUERY is just there for the pretty printing)
https://dbfiddle.uk/XgZ_IluN