Appendix B - Parsing JSON Arrays

If the JSON text string contains an array, it can be parsed into COBOL data items containing the OCCURS or OCCURS DEPENDING ON clauses.

Each JSON array should have the same number of elements as the associated table data item. If the JSON array has fewer elements, additional COBOL table elements are not modified, but if the JSON array has more values than the matching table item, the additional values are ignored. Both of these scenarios results in a nonzero JSON-STATUS setting.

Consider the following JSON text string:


If you pass the string into the following COBOL program, you can see how it can be parsed, at which point you can query and manipulate the results:

       Identification division.
       Program-id. jparse1.
       Data division.
       Working-storage section.
       01 mem-file.
           03 rec occurs 3.
               05 snd usage comp-1.
               05 pid pic 9999 usage display.
               05 txt pic x(12).
       01 cnt pic 9 value zeroes.
       Linkage section.
       01 json-str pic x(128).
       Procedure division using json-str.
       display "Parsing....".
       JSON PARSE json-str into mem-file with DETAIL
       perform 3 times
           add 1 to cnt
           if snd(cnt) equal to 9 then
               display "PID is " pid(cnt)
               display "Message text is '" txt(cnt) "'"
       display "Status is: " JSON-STATUS.
       display "Code is: " JSON-CODE.
       End program jparse1.

As a result of executing the JSON PARSE statement, the group rec is populated with the three elements from the JSON array. At this point, you can manipulate the text in any way that you wish by using the matched COBOL data item and table indices.

The special value null can be used to skip assignment of the corresponding data item or occurrence. For example, parsing the JSON text would result in setting only the third and fifth occurrences of the myTable data item:

Consider the following JSON text:

{"mt":{"myTable":[null, null, 21, null,66]}}

When the text is parsed into a COBOL table, only the third and fifth table indices are populated. A non-exception code (64) is produced for the other indices.