DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Streamlining Event Data in Event-Driven Ansible
  • Dynamic Web Forms In React For Enterprise Platforms
  • Unlocking Oracle 23 AI's JSON Relational Duality
  • Loading XML into MongoDB

Trending

  • Unlocking AI Coding Assistants Part 2: Generating Code
  • Java's Quiet Revolution: Thriving in the Serverless Kubernetes Era
  • The 4 R’s of Pipeline Reliability: Designing Data Systems That Last
  • Develop a Reverse Proxy With Caching in Go
  1. DZone
  2. Data Engineering
  3. Databases
  4. Relational to JSON With PL/SQL

Relational to JSON With PL/SQL

Using JSON with Oracle has become much easier, but what if you need to do something that needed the use of PL/SQL's procedural features?

By 
Dan McGhan user avatar
Dan McGhan
·
Nov. 09, 18 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
10.8K Views

Join the DZone community and get the full member experience.

Join For Free

In the last post in this series, I demonstrated how powerful functions added to the SQL engine in Oracle Database 12.2 allow you to generate JSON with ease. But what if you were doing something sufficiently complex that it required the procedural capabilities that PL/SQL provides? Well, you're covered there too! In this post, I'll show you how new JSON based object types can be used to get the job done.

Please Note: This post is part of a series on generating JSON from relational data in Oracle Database. See that post for details on the solution implemented below as well as other options that can be used to achieve that goal.

Solution

The 12.2+ PL/SQL object types available for working with JSON are:

  • JSON_ELEMENT_T – supertype of the other JSON types (rarely used directly)
  • JSON_OBJECT_T – used to represent JSON objects
  • JSON_ARRAY_T – used to represent JSON arrays
  • JSON_SCALAR_T – used to represent scalar values in JSON (strings, numbers, booleans, and null)
  • JSON_KEY_LIST – lesser used collection type for object keys

In the following solution, I use the JSON_OBJECT_T and JSON_ARRAY_T types to generate the desired JSON output. Smaller data structures are used to compose larger ones until I have the JSON object I want. Then I use the to_clob method to serialize the in-memory representation to JSON.

create or replace function get_dept_json(
   p_dept_id in departments.department_id%type
)

   return clob

is

   cursor manager_cur (
      p_manager_id in employees.employee_id%type
   )
   is
      select *
      from employees
      where employee_id = manager_cur.p_manager_id;

   l_date_format        constant varchar2(20) := 'DD-MON-YYYY';
   l_dept_rec           departments%rowtype;
   l_dept_json_obj      json_object_t;
   l_loc_rec            locations%rowtype;
   l_loc_json_obj       json_object_t;
   l_country_rec        countries%rowtype;
   l_country_json_obj   json_object_t;
   l_manager_rec        manager_cur%rowtype;
   l_manager_json_obj   json_object_t;
   l_employees_json_arr json_array_t;
   l_employee_json_obj  json_object_t;
   l_job_rec            jobs%rowtype;
   l_jobs_json_arr      json_array_t;
   l_job_json_obj       json_object_t;

begin

   select *
   into l_dept_rec
   from departments
   where department_id = get_dept_json.p_dept_id;

   l_dept_json_obj := json_object_t();

   l_dept_json_obj.put('id', l_dept_rec.department_id);
   l_dept_json_obj.put('name', l_dept_rec.department_name);

   select *
   into l_loc_rec
   from locations
   where location_id = l_dept_rec.location_id;

   l_loc_json_obj := json_object_t();

   l_loc_json_obj.put('id', l_loc_rec.location_id);
   l_loc_json_obj.put('streetAddress', l_loc_rec.street_address);
   l_loc_json_obj.put('postalCode', l_loc_rec.postal_code);

   select *
   into l_country_rec
   from countries cou
   where cou.country_id = l_loc_rec.country_id;

   l_country_json_obj := json_object_t();

   l_country_json_obj.put('id', l_country_rec.country_id);
   l_country_json_obj.put('name', l_country_rec.country_name);
   l_country_json_obj.put('regionId', l_country_rec.region_id);

   l_loc_json_obj.put('country', l_country_json_obj);

   l_dept_json_obj.put('location', l_loc_json_obj);

   open manager_cur(l_dept_rec.manager_id);
   fetch manager_cur into l_manager_rec;

   if manager_cur%found
   then
      l_manager_json_obj := json_object_t();

      l_manager_json_obj.put('id', l_manager_rec.employee_id);
      l_manager_json_obj.put('name', l_manager_rec.first_name || ' ' || l_manager_rec.last_name);
      l_manager_json_obj.put('salary', l_manager_rec.salary);

      select *
      into l_job_rec
      from jobs job
      where job.job_id = l_manager_rec.job_id;

      l_job_json_obj := json_object_t();

      l_job_json_obj.put('id', l_job_rec.job_id);
      l_job_json_obj.put('title', l_job_rec.job_title);
      l_job_json_obj.put('minSalary', l_job_rec.min_salary);
      l_job_json_obj.put('maxSalary', l_job_rec.max_salary);

      l_manager_json_obj.put('job', l_job_json_obj);

      l_dept_json_obj.put('manager', l_manager_json_obj);
   else
      l_dept_json_obj.put_null('manager');
   end if;

   close manager_cur;

   l_employees_json_arr := json_array_t();

   for emp_rec in (
      select *
      from employees
      where department_id = l_dept_rec.department_id
   )
   loop
      l_employee_json_obj := json_object_t();

      l_employee_json_obj.put('id', emp_rec.employee_id);
      l_employee_json_obj.put('name', emp_rec.first_name || ' ' || emp_rec.last_name);
      l_employee_json_obj.put('isSenior', emp_rec.hire_date < to_date('01-jan-2005', 'dd-mon-yyyy'));
      l_employee_json_obj.put('commissionPct', emp_rec.commission_pct);

      l_jobs_json_arr := json_array_t();

      for jh_rec in (
         select job_id,
            department_id,
            start_date,
            end_date
         from job_history
         where employee_id = emp_rec.employee_id
      )
      loop
         l_job_json_obj := json_object_t();

         l_job_json_obj.put('id', jh_rec.job_id);
         l_job_json_obj.put('departmentId', jh_rec.department_id);
         l_job_json_obj.put('startDate', to_char(jh_rec.start_date, l_date_format));
         l_job_json_obj.put('endDate', to_char(jh_rec.end_date, l_date_format));

         l_jobs_json_arr.append(l_job_json_obj);
      end loop;

      l_employee_json_obj.put('jobHistory', l_jobs_json_arr);

      l_employees_json_arr.append(l_employee_json_obj);
   end loop;

   l_dept_json_obj.put('employees', l_employees_json_arr);

   return l_dept_json_obj.to_clob();

exception

   when others
   then      
      if manager_cur%isopen
      then
         close manager_cur;
      end if;

      raise;

end get_dept_json;

Output

When passed a department id of 10, the function returns a CLOB populated with JSON that matches the goal 100%.

{
  "id": 10,
  "name": "Administration",
  "location": {
    "id": 1700,
    "streetAddress": "2004 Charade Rd",
    "postalCode": "98199",
    "country": {
      "id": "US",
      "name": "United States of America",
      "regionId": 2
    }
  },
  "manager": {
    "id": 200,
    "name": "Jennifer Whalen",
    "salary": 4400,
    "job": {
      "id": "AD_ASST",
      "title": "Administration Assistant",
      "minSalary": 3000,
      "maxSalary": 6000
    }
  },
  "employees": [
    {
      "id": 200,
      "name": "Jennifer Whalen",
      "isSenior": true,
      "commissionPct": null,
      "jobHistory": [
        {
          "id": "AD_ASST",
          "departmentId": 90,
          "startDate": "17-SEP-1995",
          "endDate": "17-JUN-2001"
        },
        {
          "id": "AC_ACCOUNT",
          "departmentId": 90,
          "startDate": "01-JUL-2002",
          "endDate": "31-DEC-2006"
        }
      ]
    }
  ]
}

Summary

The JSON types for PL/SQL are a very welcome addition to Oracle Database. I've only demonstrated how to build up objects in memory to generate JSON, but there are many other methods for modification, serialization, introspection, and so on.

If you've seen the PL/JSON solution, you'll note that the code is very similar since they both use the object-oriented capabilities of Oracle Database (as opposed to APEX_JSON which is more procedural). When compared to PL/JSON, the main advantages to the 12.2+ built-in types are:

  • Simplicity: There's no installation needed.
  • Documentation: The JSON Developer's Guide provides some getting started content in Part IV: PL/SQL Object Types for JSON and the PL/SQL Packages and Types Reference provides additional API details.
  • Performance: I ran a small test on a local 18c XE database where I generated the JSON for each department in the HR schema 100 times. The PL/JSON solution took about 4.6 seconds on average while the solution in this post and the APEX_JSON solution both took around 1.5 seconds.

Having said all that, if you're not yet using Oracle Database 12.2+, then PL/JSON is still a great option for working with JSON. The PL/JSON team continues to build out the APIs, address issues, and develop the documentation.

JSON PL/SQL

Published at DZone with permission of Dan McGhan, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Streamlining Event Data in Event-Driven Ansible
  • Dynamic Web Forms In React For Enterprise Platforms
  • Unlocking Oracle 23 AI's JSON Relational Duality
  • Loading XML into MongoDB

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!