I need to parse JSON using Oracle SQL select. Here is my JSON:
{"result":[
{
"field_name1":{"display_value":"TEST1","link":"https://test1.com","value":"abcd"},
"field_name2":{"display_value":"","link":"","value":""},
"field_name3":{"display_value":"TEST3","link":"https://test3.com","value":"efgh"},
"field_name4":{"display_value":"TEST4","link":"https://test3.com","value":"ijkl"}
}
]}
I want to get results as follows:
field_name1:abcd
field_name3:efgh
field_name4:ijkl
excluding those that have nulls in the value
.
How an I accomplish that? I tried using JSON_TABLE
but was not able to because I do not know the column names ahead of time.
2
Answers
You can use:
Which, for the sample data:
Outputs:
fiddle
For small data set, the solution with the get_key function is fine, but be aware that it also means parsing the whole JSON once per possible key.
If you want to parse it a minimum of times , you would need to use json_dataguide to generate the paths:
returns:
Then use the results to generate a SQL that will use json_table, e.g. here to get the results as simple strings "key:value":
Then eventually pass the SQL string to a table function that will fetch the data using a dynamic cursor and return the result in the format you want, that may need the definition of an OBJECT if you want columns.
Then the original JSON will be parsed only 2 times per "result[0]" to parse.
This way requires a little bit more work to implement, but may pay off on large data set (lot of "result" rows each one with lot of "fieldname").
Example to fetch results as simple string: