设为首页 收藏本站
查看: 468|回复: 0

[经验分享] Oracle and JSON: Using PL/JSON

[复制链接]

尚未签到

发表于 2016-7-28 09:38:55 | 显示全部楼层 |阅读模式
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 thereference 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/. Unzipthe 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 is26). 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 emptyjson_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 ofthe array is printed as output. Next, you loop through the JSON array itself, and print out the object_type and count properties for each itemin the list. The overall output should look as follows:
[{

  "object_type" : "IndexPartition",

  "count" : 99

}, {

  "object_type": "Index",

  "count": 1411

}, {

  "object_type" : "Indextype",

  "count" : 8

}]


Index Partition->99

Index->1411

  Indextype->8

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-250496-1-1.html 上篇帖子: Oracle调优之shared pool相关 下篇帖子: ORACLE数据库命名规范(转)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表