Oracle and JSON: Using PL/JSON

Oracle and JSON: Using PL/JSON

JSON (JavaScript. Object Notation) is a lightweight data format that is very well suited for transmitting data over the Internet. Despite the reference to JavaScript. in its name, JSON is a language-independent syntax and native support for it has been included in many modern programming languages. In fact, JSON is so popular nowadays that entire database management systems have built their record structure around it, for example Apache CouchDB .

As a Web developer who does a lot of work with PL/SQL, I have recently found myself creating PL/SQL procedures that output JSON data, and making these procedures available as RESTful HTTP services that are then consumed by Ajax functions in the front-end of my applications. This can be a bit of a pain, however, as I need to output the JSON data manually, making it very prone to errors and very difficult to debug in many cases.

Thankfully, an open source library for PL/SQL called PL/JSON is available that resolves some of the issues associated with working with JSON data in an Oracle application. In this post, you will learn how to install and use PL/JSON to work with JSON data in your own PL/SQL applications.

Download and install the library

The latest version of PL/JSON, at the time of writing, is version 0.8.6. The compressed archive is less than 200KB in size. You can download PL/JSON from SourceForge at http://sourceforge.net/projects/pljson/files/ . Unzip the library to your hard drive and install it in a SQL*Plus session using the following command:

@install

You should see the following output:

-----------------------------------
-- Compiling objects for PL/JSON --
-----------------------------------
PL/SQL procedure successfully complete
Type created.
No errors.
Type body created.
No errors.
Type created.
No errors.
Type body created.
No errors.
Type created.
No errors.
Type created.
No errors.
Type created.
No errors.
Type created.
No errors.
Type created.
No errors.
Type created.
No errors.
Package created.
Package body created.
Package created.
Package body created.
Type body created.
No errors.
Type body created.
No errors.
Package created.
Package body created.

Assuming you see no errors from running the install script, PL/JSON is now installed in your Oracle database.

Using PL/JSON

With PL/JSON installed, you can now start working with the traditional “Hello, world” example, using the following PL/SQL code:


01set serveroutput on
02declare
03     jsonObj        json;
04begin
05     --Create a new JSON object, passing the JSON code as the constructor
06     jsonObj := json('{"greeting":"Hello World"}');
07     --Output the value for the JSON data with the key "greeting"
08     dbms_output.put_line(json_ext.get_varchar2(jsonObj, 'greeting'));
09end;
10/

This produces the following output:

Hello, World

As you can see from the above output, PL/JSON parses JSON data. But what if you want to create a JSON object without actually providing the data in JSON format. Take the following example:


01set serveroutput on
02declare
03     jsonObj       json;
04begin
05     --Use an empty constructor to create a blank JSON object
06     jsonObj := json();
07     -- Use the put procedure to add a string, number, boolean and null property to the JSON object
08     jsonObj.put('name', 'Joe Lennon');
09     jsonObj.put('age', 24);
10     jsonObj.put('awesome', json_bool(true));
11     jsonObj.put('children', json_null());
12
13     --Print the string representation of the JSON object (pretty-print)
14     jsonObj.print;
15     dbms_output.put_line('Am I awesome?');
16     --Use getters to retrieve the value of the boolean property "awesome" and print the result
17     dbms_output.put_line(json_ext.get_json_bool(jsonObj, 'awesome').to_char);
18end;
19/

The output for the above looks like:

{
   "name" : "Joe Lennon",
   "age" : 24,
   "awesome" : true,
   "children" : null
}
Am I awesome?
true

JSON Arrays

JSON objects can contain data in several types – number, string, boolean, null or array. At this point, you’ve seen how to work with the first four of these types, but not arrays. PL/JSON refers to these as a json_list. Working with json_list objects is very similar to working with a regular JSON object, as shown in the following example:


01set serveroutput on
02declare
03     jsonArray        json_list;
04     jsonObj           json;
05begin
06     jsonArray := json_list('[{"name":"Joe","age":24},{"name":"Jill","age":26}]');
07     jsonObj := json.to_json(jsonArray.get_elem(1));
08     dbms_output.put_line(json_ext.get_varchar2(jsonObj, 'name'));
09     jsonObj := json.to_json(jsonArray.get_elem(2));
10     dbms_output.put_line(to_char(json_ext.get_number(jsonObj, 'age')));
11end;
12/

The above code create a JSON array (or json_list) containing two objects with two properties, name and age. The first object has the name “Joe” and age 24, the second has name “Jill” and age 26. The get_elem function is used to return an item in the JSON array, and the to_json function casts this is a JSON object. In the above example, you first assign jsonObj to the first object in the JSON array, printing out the value of the name property for this object (in this case, the string value “Joe”). Next, you assign jsonObj to the second object in the array, and print out the value of the age property (in this case, age is 26). The output for this example is as follows:

Joe
26

To wrap up this post, let’s have a look at a more complex scenario for using JSON in PL/SQL. Let’s say that you want to create a JSON representation of the result of a SQL statement. The following example demonstrates just that:


01set serveroutput on
02declare
03     jsonArray     json_list;
04     jsonObj       json;
05
06     cursor get_data is
07         select initcap(lower(object_type)) name, count(*) count
08         from all_objects
09         where upper(object_type) like 'INDEX%'
10         group by object_type;
11begin
12    jsonArray := json_list();
13    for objType in get_data loop
14        jsonObj := json();
15        jsonObj.put('object_type', objType.name);
16        jsonObj.put('count', objType.count);
17        jsonArray.add_elem(jsonObj.to_anydata);
18    end loop;
19
20    jsonArray.print;
21
22    dbms_output.new_line;
23
24    for i in 1..jsonArray.count loop
25        dbms_output.put_line(
26            json_ext.get_varchar2(
27                json.to_json(jsonArray.get_elem(i)),
28                'object_type'
29            )||'->'||
30            to_char(json_ext.get_number(
31                json.to_json(jsonArray.get_elem(i)),
32                'count'
33            ))
34        );
35    end loop;
36end;
37/

In the example above, you first initialize the JSON array to an empty json_list. Next, you loop through the get_data cursor, which selects back the counts for all object types in the database that begin with “INDEX”. For each iteration of this loop, a JSON object is created, the object type name and count are added as properties to the object, and the object is added to the JSON array. Then the string representation of the array is printed as output. Next, you loop through the JSON array itself, and print out the object_type and count properties for each item in the list. The overall output should look as follows:

[{
   "object_type" : "Index Partition",
   "count" : 99
}, {
   "object_type": "Index",
   "count" : 1411
}, {
   "object_type" : "Indextype",
   "count" : 8
}]
Index Partition->99
Index->1411

Indextype->8

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/11893231/viewspace-672462/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/11893231/viewspace-672462/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值