JSON and XML

JSON PARSE

COBOL 2014 added JSON. JSON PARSE reads a JSON document into a data item whose structure mirrors the document, mapping objects to groups and arrays to OCCURS.

GnuCOBOL 3.2 accepts a JSON PARSE statement but does not implement it: the compiler warns that JSON PARSE is not implemented and the statement does nothing at run time. On this compiler, parse JSON with a C helper or upgrade to a GnuCOBOL release that implements it.

JSON GENERATE

JSON GENERATE writes a data item out as a JSON document, mapping groups to objects and OCCURS tables to arrays. It works in GnuCOBOL 3.2 and is the other half of a REST client: generate the request out, and parse the response with a helper. Save this program as jsonout.cob:

IDENTIFICATION DIVISION. PROGRAM-ID. JSONOUT. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-REQUEST. 05 WS-NAME PIC X(10) VALUE "Ada". 05 WS-ROLE PIC X(10) VALUE "analyst". 01 WS-OUT-DOC PIC X(200). PROCEDURE DIVISION. JSON GENERATE WS-OUT-DOC FROM WS-REQUEST ON EXCEPTION DISPLAY "Generate failed". DISPLAY FUNCTION TRIM(WS-OUT-DOC). STOP RUN.

cobc -x -free -o jsonout jsonout.cob

./jsonout

{"WS-REQUEST":{"WS-NAME":"Ada","WS-ROLE":"analyst"}}

The keys are the COBOL names, because JSON GENERATE uses the data names as they are. Name the fields the way the API expects them before you generate the document.

XML PARSE

XML PARSE walks an XML document and calls a handler paragraph at each start-of-element, character, and end-of-event. It is lower level than JSON PARSE, and still the way to read legacy XML feeds.

GnuCOBOL 3.2 does not implement XML PARSE either: it warns and rejects the standard XML PARSE ... PROCESSING PROCEDURE form. Use a C helper linked through CALL, or a compiler that implements the statement.

The JSON GENERATE example on this page was run with GnuCOBOL 3.2.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container. JSON PARSE and XML PARSE are not implemented in this compiler.

Article author: Arthur Isaev