18
Thu, Apr
5 New Articles

TechTip: Work with JSON Arrays in DB2 for i

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

Learn how to parse DB2 for i JSON using JSON_TABLE and JSON_TABLE_BINARY.

 

In my previous JSON tip, I introduced DB2's new ability to store and parse JSON data using SQL in DB2 for i. This tip continues the topic of JSON parsing by discussing the JSON_TABLE and JSON_TABLE_BINARY table functions and their ability to process JSON arrays.

 

 

If you're unfamiliar with JSON in DB2 for i, please review my prior TechTip as it discusses the IBM i prerequisites, the initial JSON setup, and the concept of casting JSON to BSON when storing JSON documents in DB2. Today's tip assumes you have some familiarity with the JSON_VAL scalar function and storing JSON data as BSON. Finally, note that the JSON features at this release are being called a technology preview and are therefore subject to change. So test carefully before using the JSON features in production.

 

Extracting Data Element Arrays

 

In the prior tip's JSON parsing example, the JSON document was simple so that the JSON_VAL scalar function could be used to extract the required data to build a single-row result set. However, what if you have a JSON document like the one below, describing donut variations with nested arrays for dough batters and toppings? IBM's answer is to use the JSON_TABLE table function. Similar to XMLTABLE, JSON_TABLE can extract and return a list of elements in tabular form.

 

 

In this example, the batter types will be extracted using the JSON_TABLE function. Keep in mind, as with XMLTABLE, sometimes you may need to process the JSON document multiple times in order to extract all of the array items in tabular form.

 

 

 

-- Sample JSON doc from

 

-- http://adobe.github.io/Spry/samples/data_region/JSONDataSetSample.html

 

SELECT *

 

FROM TABLE(SYSTOOLS.JSON_TABLE(

 

SYSTOOLS.JSON2BSON('

 

{

 

      "id": "0001",

 

      "type": "donut",

 

      "name": "Cake",

 

      "ppu": 0.55,

 

      "batters":

 

            {

 

                  "batter":

 

                        [

 

                              { "id": "1001", "type": "Regular" },

 

                              { "id": "1002", "type": "Chocolate" },

 

                              { "id": "1003", "type": "Blueberry" },

 

                              { "id": "1004", "type": "Devil''s Food" }

 

                        ]

 

            },

 

      "topping":

 

            [

 

                  { "id": "5001", "type": "None" },

 

                  { "id": "5002", "type": "Glazed" },

 

                  { "id": "5005", "type": "Sugar" },

 

                  { "id": "5007", "type": "Powdered Sugar" },

 

                  { "id": "5006", "type": "Chocolate with Sprinkles" },

 

                  { "id": "5003", "type": "Chocolate" },

 

                  { "id": "5004", "type": "Maple" }

 

            ]

 

}'),'batters.batter.type','s:32')) Data

 

;

 

 

 

JSON_TABLE accepts the same three arguments as JSON_VAL: BSON data, the element to extract, and the resulting data type. The table function returns two columns: type and value. The results of the above query are shown here:

 

 

 

TYPE

VALUE

2

Regular

2

Chocolate

2

Blueberry

2

Devil's Food

 

 

 

The value column is, of course, the requested JSON element's value. The type column is a little bit more difficult to interpret (and at the time of this writing, I couldn't find any documentation on this table function). After some experimentation with JSON_TABLE, the following type values have been identified:

 

 

 

Type

Description

1

number (e.g., 0.123, 3.122e15)

2

String

3

object / array

8

Boolean

10

Null

16

Integer

 

 

 

To recap, the TYPE column will assist you in deciding which DB2 data type to use to store the element's value.

 

 

 

In this next example using the same JSON "donut data," the topping variations (elements id and type) will be extracted with the top level "donut" item information (type, name, ppu). Instead of using JSON_TABLE, this example will use JSON_TABLE_BINARY, which is similar to JSON_TABLE except its VALUE column returns BSON instead of VARCHAR.

 

 

 

WITH DONUT_DATA(JSON_INFO) AS (

 

SELECT * FROM (VALUES(SYSTOOLS.JSON2BSON('

 

{

 

      "id": "0001",

 

      "type": "donut",

 

      "name": "Cake",

 

      "ppu": 0.55,

 

      "batters":

 

            {

 

                  "batter":

 

                        [

 

                              { "id": "1001", "type": "Regular" },

 

                              { "id": "1002", "type": "Chocolate" },

 

                              { "id": "1003", "type": "Blueberry" },

 

                              { "id": "1004", "type": "Devil''s Food" }

 

                        ]

 

            },

 

      "topping":

 

            [

 

                  { "id": "5001", "type": "None" },

 

                  { "id": "5002", "type": "Glazed" },

 

                  { "id": "5005", "type": "Sugar" },

 

                  { "id": "5007", "type": "Powdered Sugar" },

 

                  { "id": "5006", "type": "Chocolate with Sprinkles" },

 

                  { "id": "5003", "type": "Chocolate" },

 

                  { "id": "5004", "type": "Maple" }

 

            ]

 

}

 

'))) temp)

 

SELECT JSON_VAL(d.JSON_INFO,'type','s:32') AS Type,

 

       JSON_VAL(d.JSON_INFO,'name','s:32') AS Name,

 

       JSON_VAL(d.JSON_INFO,'ppu','f') AS PPU,

 

       JSON_LEN(d.JSON_INFO,'topping') AS No_Toppings,

 

       JSON_VAL(TOPPING_DATA.VALUE,'id','i') AS Topping_Id,

 

       JSON_VAL(TOPPING_DATA.VALUE,'type','s:64') AS Topping_Type

 

FROM DONUT_DATA d

 

CROSS JOIN TABLE(

 

SYSTOOLS.JSON_TABLE_BINARY(d.JSON_INFO,'topping','s:64')) TOPPING_DATA

 

;

 

 

 

The query returns this result set:

 

 

 

Type

Name

PPU

Topping_Id

Topping_Type

donut

Cake

0.55

5001

None

donut

Cake

0.55

5002

Glazed

donut

Cake

0.55

5005

Sugar

donut

Cake

0.55

5007

Powdered Sugar

donut

Cake

0.55

5006

Chocolate with Sprinkles

donut

Cake

0.55

5003

Chocolate

donut

Cake

0.55

5004

Maple

 

 

 

Notice that JSON_TABLE_BINARY was passed the "topping" element (second argument), which is itself an array with each element in the array looking like this: { "id": "5002", "type": "Glazed" }. The table function will return one row for each element in the array in BSON format. Since the VALUE column contains BSON, the JSON_VAL scalar function can be used to extract individual data elements.

 

 

 

You may have noticed the result type parameter passed to the JSON_TABLE and JSON_TABLE_BINARY functions includes a type and a string length (e.g., 's:64'). The length is important as it instructs the table function on how much space to allocate for a string. In the DB2 examples I found online, the JSON_VAL function also required the length. When investigating JSON_VAL on DB2 for i, I found that while the length can be specified in DB2 for i, it is currently ignored.

 

An additional useful JSON array function is JSON_LEN.  JSON_LEN accepts BSON data and an element and returns the number of elements in the requested array.  Assuming that global variable ADVWORKS.JSON_DONUT is defined as a BLOB(64K) and contains the BSON version of the JSON donut data illustrated above:  

 

VALUES (

SYSTOOLS.JSON_LEN(ADVWORKS.JSON_DONUT,'batters.batter'),

SYSTOOLS.JSON_LEN(ADVWORKS.JSON_DONUT,'topping')

);

 

This example will return integer values of four and seven, because there are four batters and seven toppings defined in the JSON data.

 

 

In conclusion, use JSON_TABLE for extracting single primitive elements (text and numbers) from an array. JSON_TABLE_BINARY can be used to extract the entire array element, and then JSON_VAL can be used to extract the individual elements.

 

 

References

 

TechTip: Store and Parse JSON Data Natively with DB2 for i

 

 

 

IBM DB2 for i: JSON Store Technology PreviewA comprehensive overview of the JSON features available for IBM i

 

Four-Part Series on DB2 JSON capabilities (Note: not all of the described JSON capabilities are available in DB2 for i. Article 3 of this series describes the Java API that can be used to compose JSON documents.)

 

 

 

TechTip: JSON and XML Conversion in DB2 for i

 


TechTip: Check Out the New DB2 for i HTTP Functions

 

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: