Search notes:

Oracle: PL/SQL package JSN to assist in creation of JSON data

This package depends on TIM.
I have written this package before I familiarized myself with functions like json_scalar, json_array or json_object. In hindsight, it seems that I should have used functions like these rather than writing a package to manage JSON data.

Source code

Specification

create or replace package jsn as
 --
 -- V0.2
 --

    function val(text varchar2) return clob;

    function val(val number) return clob;

    function name_value(name varchar2, value varchar2) return clob;

    function name_value(name varchar2, value clob) return clob;

    function name_value(name varchar2, value date) return clob;

    function name_value(name varchar2, value boolean) return clob;

    function name_value(name number, value varchar2) return clob;

end jsn;
/
Github repository PL-SQL-pkg-jsn, path: /spec.sql

Body

create or replace package body jsn as
 --
 -- V0.2
 --

    function val(text varchar2) return clob is -- {
    begin
        return '"' || replace(text, '"', '\"') || '"';
    end val; -- }

    function val(val number) return clob is -- {
    begin

        if val <= -1 or val >= 1 then
           return to_char(val);
        end if;

        if val < 0 then
           return '-0' || to_char(abs(val));
        else
           return '0' || to_char(     val );
        end if;

    end val; -- }

    function name_value(name varchar2, value varchar2) return clob is
    begin
         return '"' || name || '": "' || value || '"';
    end name_value;

    function name_value(name varchar2, value clob) return clob is
    begin
         return '"' || name || '": "< CLOB > "';
    end name_value;

    function name_value(name varchar2, value date) return clob is
    begin
         return name_value(name, tim.iso_8601(value));
    end name_value;

    function name_value(name varchar2, value boolean) return clob is -- {
    begin

         if value then
            return val(name) || ': true';
         end if;

         if not value then
            return val(name) || ': false';
         end if;

         return val(name) || ': null';

    end name_value; -- }

    function name_value(name number, value varchar2) return clob is -- {
    begin
         return '"' || name || '": "' || value || '"';
    end name_value; -- }

end jsn;
/

show errors
Github repository PL-SQL-pkg-jsn, path: /body.sql

History

V0.2 make sure that val(number) returns a leading zero if in the range -1 … 1 (JSON does not allow leading decimal points for numbers, but Oracle's to_char() returns a leading decimal point for number between -1 and 1).

See also

JSON
Other simple PL/SQL packages I've written over time.

Index