Archive · 17 January 2015
Generate nested JSON from SQL with ORDS and APEX 5
Written 11 years ago. Oracle APEX has moved on a lot since; check the current Oracle APEX posts too.
When creating web applications, at some point you will need to interact with JSON. Either you consume JSON or you need to generate it to be able to use that cool widget you found.
A few years ago when I wrote about interacting and customising charts, XML was the data format. Today JSON is more common to use as it works so well with JavaScript. I needed to pass some nested JSON - here’s an example: multiple customers have multiple orders and an order consists out of multiple items:

What is the easiest way to generate that JSON data?
Luckily we have Oracle REST Data Services (ORDS), it literally is just one SQL statement!
Here you go:

Save and presto you’re done :) Hit the TEST button and copy/paste the generated JSON in for example JSONLint to validate the output and yep we have valid JSON.

But that is not all - it gets even better. APEX 5 comes with a new package apex_json which contains so many goodies, really a wonderful piece of code. The same SQL statement I call with the package and again I get the JSON I need. It’s slightly different from what ORDS generated - ORDS has an items tag surrounding the data, but again it’s valid JSON.
Note that APEX 4.2 has some JSON support too (apex_util.json_from_sql), but it doesn’t go as far as the package you find in APEX 5.0 - for example the cursor syntax is not working there, but for straight forward JSON it does it job.

So this shows how easy it is to generate JSON these days. It has been different where we had to use the PL/JSON package (which was good too, but build-in is what I prefer).
And finally with Oracle Database 12c, and the JSON support straight in the database, consuming and querying JSON has been made so much easier, but that is for another post. If you can’t wait, the link will bring you to the official 12c Database JSON doc.
Originally published on Blogspot.
Comments
No comments yet. Be the first.