25
Thu, Apr
1 New Articles

TechTip: JSON and XML Conversion in DB2 for i

General
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

 

Use the java-json library to easily convert between XML and JSON formats.

 

As I noted in my article on SOA and REST, JavaScript Object Notation (JSON) is an important data format in today's world of RESTful service offerings. Whether your apps are publishing or consuming data, you may be asked to work with JSON. This tip offers an "el cheapo" technique on how to transform JSON to XML and vice versa, because XML is easy to work with in the RPG ILE and DB2 for i environment.

 

Many REST services offer XML and JSON data formats, but as of late I've noticed many of these services offering only JSON. With JSON, the world is good if you're a JavaScript developer but not so good if you're using a language that doesn't know anything about JSON processing.

 

Say for instance you're browsing through Google's JSON developer's guide and you find an image search REST API you want to incorporate into your application using the HTTPGETCLOB function:

 

SELECT data FROM

(VALUES(SYSTOOLS.HTTPGETCLOB

('https://ajax.googleapis.com/ajax/services/search/images?v=1.0&;q=fuzzy%20monkey',''))) WS(data);

           

Accessing this Google API will only get you a nice JSON response (shown below), but what does DB2 for i or even RPG know about JSON?

 

{

"responseData":{

   "results":[

     {

       "GsearchResultClass":"GimageSearch",

       "width":"1152",

       "height":"864",

       "imageId":"ANd9GcQQigy-U6KTXke82n5hma5qvFM2UyVnkGtJme6pkZgl_1GYM--Yb90oqnOJ",

       "tbWidth":"150",

       "tbHeight":"113",

       "unescapedUrl":"http://www.blirk.net/wallpapers/1152x864/fuzzy-monkey-1.jpg",

       "url":"http://www.blirk.net/wallpapers/1152x864/fuzzy-monkey-1.jpg",

       "visibleUrl":"stackoverflow.com",

       "title":"\u003cb\u003efuzzy\u003c/b\u003e-\u003cb\u003emonkey

\u003c/b\u003e-1.jpg",

       "titleNoFormatting":"fuzzy-monkey-1.jpg",

       "originalContextUrl":"http://stackoverflow.com/questions/17773949/

rails-best-way-to-extract-values-from-response-hash",

       "content":"\u003cb\u003efuzzy\u003c/b\u003e-\u003cb\u003emonkey\u003c/b\u003e-1.jpg",

       "contentNoFormatting":"fuzzy-monkey-1.jpg",

       "tbUrl":"http://t1.gstatic.com/images?q\u003dtbn:ANd9GcQQigy-

U6KTXke82n5hma5qvFM2UyVnkGtJme6pkZgl_1GYM--Yb90oqnOJ"

     },

...more data...

   ],

   "cursor":{

     "resultCount":"2,760,000",

     "pages":[

       {

         "start":"0",

         "label":1

      },

...more data...

     ],

     "estimatedResultCount":"2760000",

     "currentPageIndex":0,

     "moreResultsUrl":"http://www.google.com/images?oe\u003dutf8\u0026ie\u003dutf8\u0026source\u003duds\u0026start\u003d0\u0026hl\u003den\u0026q\u003dfuzzy+monkey",

     "searchResultTime":"0.39"

   }

},

"responseDetails":null,"responseStatus":200

}
JSON to XML

Fortunately, thanks to a free Java library called java-json, code is available to convert JSON into XML so that it can be used by DB2 for i and, by extension, any of the ILE languagessuch as RPG, C, or COBOLusing embedded SQL. If you're not a Java developer, don't worry. All you have to do is compile the code once, and from there you never have to worry about Java again as it will stay "under the covers."

 

I have created an external user-defined function (UDF) called JSON2XML that will accept a string (CLOB data type) and return XML (as a CLOB). A sample invocation that wraps the prior example is shown here:

 

SELECT QGPL.JSON2XML(data) AS XMLData FROM (VALUES(SYSTOOLS.HTTPGETCLOB('https://ajax.googleapis.com/ajax/services/search/images?v=1.0&;q=fuzzy%20monkey',''))) WS(data);

 

The JSON data is retrieved from the image search API and then put through the JSON2XML function to convert it to XML. The transformed JSON now looks like the following in XML:

 

<responseData>

<cursor>

<moreResultsUrl>http://www.google.com/images?oe=utf8&;amp;ie=utf8&amp;source=uds&amp;start=0&amp;hl=en&amp;q=fuzzy+monkey</moreResultsUrl>

… more goes here …

</cursor>

<results>

<titleNoFormatting>fuzzy-monkey-1.jpg</titleNoFormatting>

<tbUrl>http://t1.gstatic.com/images?q=tbn:ANd9GcQQigy-U6KTXke82n5hma5qvFM2UyVnkGtJme6pkZgl_1GYM--Yb90oqnOJ</tbUrl>

<originalContextUrl>http://stackoverflow.com/questions/17773949/rails-best-way-to-extract-values-from-response-hash<;/originalContextUrl>

<width>1152</width>

<unescapedUrl>http://www.blirk.net/wallpapers/1152x864/fuzzy-monkey-1.jpg<;/unescapedUrl>

<url>http://www.blirk.net/wallpapers/1152x864/fuzzy-monkey-1.jpg<;/url>

<visibleUrl>stackoverflow.com</visibleUrl>&lt;b&gt;fuzzy&lt;/b&gt;-&lt;b&gt;monkey&lt;/b&gt;-1.jpg

<GsearchResultClass>GimageSearch</GsearchResultClass>

<tbWidth>150</tbWidth>

<title>&lt;b&gt;fuzzy&lt;/b&gt;-&lt;b&gt;monkey&lt;/b&gt;-1.jpg</title>

<height>864</height>

<imageId>ANd9GcQQigy-U6KTXke82n5hma5qvFM2UyVnkGtJme6pkZgl_1GYM--Yb90oqnOJ</imageId>

<contentNoFormatting>fuzzy-monkey-1.jpg</contentNoFormatting>

<tbHeight>113</tbHeight>

</results>

<results>  … more results here … </results>

</responseData>

<responseDetails>null</responseDetails>

<responseStatus>200</responseStatus>

 

With this simple UDF, any JSON REST API can now also return XML! Thereafter, using the built-in XML functionality in IBM i 7.1, it becomes a snap to parse the XML:

 

WITH SEARCH_RESULTS AS (

SELECT '<root>'||QGPL.JSON2XML(data)||'</root>' AS XMLData FROM (VALUES(SYSTOOLS.HTTPGETCLOB('https://ajax.googleapis.com/ajax/services/search/images?v=1.0&;q=AS400',''))) WS(data)

)

SELECT WebServiceResult.*

 FROM SEARCH_RESULTS,

      XMLTABLE('$doc/root/responseData/results'

      PASSING

      XMLPARSE(DOCUMENT XMLData) AS "doc"

COLUMNS

     titleNoFormatting VARCHAR(128) PATH 'titleNoFormatting',

     ThumbNailUrl VARCHAR(1024) PATH 'tbUrl',

     originalContextUrl VARCHAR(1024) PATH 'originalContextUrl',

     width INT PATH 'width',

     length INT PATH 'width',

     height INT PATH 'height'

) AS WebServiceResult;

 

Notice that I added a root element (which the Java code does not do) so that XMLPARSE would accept the XML string as a valid document. Thereafter, XMLTABLE is used to break out the desired elements into a tabular format. The results of the above query are shown here:

 

102414SansoterraJSON-Figure1
Figure 1:
These are the results of the Google REST API query.

 

If you're not on IBM i 7.1 yet, alternatively, the XML can be parsed using RPG.

 

There is much more to this Google image search API than shown here (such as whether or not there is more data to retrieve, etc.), but this query shows the basics of how to parse the main data. Given that many JSON-based REST API results will need to be analyzed multiple times for things like a response code, current data, whether or not more data is available with another call, etc., I suggest calling the API once and persisting the XML in a variable. With the response persisted, you don't have to go through the expense of invoking the API multiple times to analyze the various values.

 

XML to JSON

The java-json library also provides a way to create JSON data from XML. Therefore I decided to throw in a related UDF called XML2JSON to take advantage of this feature. This UDF accepts an XML string (as a CLOB) and returns a JSON string (as a CLOB).

 

The UDF can be invoked as follows:

 

SELECT QGPL.XML2JSON(CLOB('<mybigXMLstring />')) AS JSONData

 FROM SYSIBM.SYSDUMMY1;

 

Incidentally, because of the improved UDF resolution, the CLOB cast is not required in IBM i 7.2.

 

This example assumes you already have an XML string ready to transform to JSON. You can also indirectly create JSON from a relational database query that uses the DB2 for i 7.1 XML composition features:

 

SELECT QGPL.XML2JSON(

XMLSERIALIZE(XMLAGG(XMLROW(

CUSNUM AS "CustomerId",

RTRIM(LSTNAM) AS "Name",

ZIPCOD AS "ZipCode",

BALDUE AS "BalDue"

OPTION ROW "Customer")) AS CLOB)) AS JSON

FROM QIWS.QCUSTCDT;

 

The resulting JSON (abridged and formatted) is shown here:

 

{"Customer":

[{"Name":"Henning","CustomerId":938472,"ZipCode":75217,"BalDue":37},

{"Name":"Jones","CustomerId":839283,"ZipCode":13041,"BalDue":100},

{"Name":"Vine","CustomerId":392859,"ZipCode":5046,"BalDue":439},

… more here …

{"Name":"Abraham","CustomerId":583990,"ZipCode":56342,"BalDue":500}

]}

 

Installing the Java UDFs

The Java code called JSON_UDFs.java is available for download. The user-defined functions should work on V5R4 and later, but use of the DB2 for i XMLTABLE table function requires IBM i 7.1 (and for best results, make sure the latest database group PTF package has been loaded).

 

The instructions for compiling the Java code are in the source code's header. Remember, as noted in the instructions, a standalone Java class intended for use by DB2 for i should be placed in this special folder: /qibm/userdata/os400/sqllib/function

 

In addition to the source code, you'll need to download the java-json.jar package from this link.

 

Once downloaded, unzip the jar file and put it in your jar folder on the IFS (for simplicity, I just used /tmp for my jar and Java source file). Unless you include the jar as part of your default class path, you'll need to make the jar available for use with DB2 using the install_jar procedure (overriding the jar path and schema as needed):

 

call sqlj.install_jar ('file:/tmp/java-json.jar','QGPL.java-json',0)

 

A commit statement is required after calling the install_jar procedure:

 

commit

 

Once the class and jar files are in place for DB2 to use, the remaining work is to define the external functions using the CREATE FUNCTION statement. This step tells DB2 how to get to the Java code:

 

CREATE OR REPLACE FUNCTION QGPL.JSON2XML(JSONData CLOB)

RETURNS CLOB

SPECIFIC QGPL.JSON2XML_CLOB

EXTERNAL NAME 'UDFs.convertJSON2XML'

LANGUAGE Java

PARAMETER STYLE Java

FENCED

NO SQL

RETURNS NULL ON NULL INPUT

SCRATCHPAD

DETERMINISTIC

 

CREATE OR REPLACE FUNCTION QGPL.XML2JSON(XMLData CLOB)

RETURNS CLOB

SPECIFIC QGPL.XML2JSON_CLOB

EXTERNAL NAME 'JSON_UDFs.convertXML2JSON'

LANGUAGE Java

PARAMETER STYLE Java

FENCED

NO SQL

RETURNS NULL ON NULL INPUT

SCRATCHPAD

DETERMINISTIC

 

The UDFs should now be available for use with DB2.

 

Caveats

  • If you don't have the opportunity to optimize or manipulate the source JSON or XML, then the resulting XML or JSON data may be suboptimal.
  • This utility is meant to be "easy." However, if performance is an issue or if strict control over the JSON output is required, I'd use a library like Scott Klement's YAJL for creating or parsing JSON.
  • This UDF has the capacity to be quite a memory hog. If you're transforming large XML or JSON strings, use it carefully or use YAJL.

 

Conclusion

Working with JSON is fast becoming a way of life when retrieving data from external systems. While JSON isn't terribly difficult to construct, it can be a pain in the neck to consume without a helper library. DB2 for i developers can take advantage of the java-json library to convert between XML and JSON, thereby making the task of working with JSON data a little easier.

 

Michael Sansoterra is a DBA for Broadway Systems in Grand Rapids, Michigan. He can be contacted at This email address is being protected from spambots. You need JavaScript enabled to view it..


BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: