BudiBadu Logo
Samplebadu

COBOL by Example: JSON Parsing

COBOL 2002

Parsing JSON text into COBOL variables with JSON PARSE INTO statement, mapping JSON keys to COBOL field names by matching identifiers, leveraging automatic type conversion from JSON types to COBOL data types, consuming modern web API responses easily, and using NAME OF phrase for field name translation.

Code

       IDENTIFICATION DIVISION.
       PROGRAM-ID. JSON-PRS.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  JSON-TXT    PIC X(50) VALUE '{"id": 5, "active": true}'.
       01  DATA-REC.
           05 id       PIC 9.
           05 active   PIC X(5).
       
       PROCEDURE DIVISION.
           JSON PARSE JSON-TXT INTO DATA-REC.
           DISPLAY "ID: " id.
           DISPLAY "Active: " active.
           STOP RUN.

Explanation

JSON PARSE automatically maps JSON fields to COBOL variables with matching names. It is much simpler than XML parsing because it often doesn't require an event loop; it can deserialize an entire object tree directly into a matching COBOL group item.

The parser matches JSON keys (e.g., "id") to COBOL data names (e.g., id). It handles type conversion where possible, such as converting a JSON number to a COBOL numeric field. If the names don't match exactly, you can use the NAME OF phrase to create a mapping.

This feature allows COBOL programs to easily consume data from modern web APIs. You simply define a Data Division structure that mirrors the JSON response, and one command populates it with data.

Code Breakdown

12
JSON PARSE JSON-TXT. Starts the parsing of the input string.
12
INTO DATA-REC. The target structure. The parser looks for fields in DATA-REC that match the keys in the JSON.
13
DISPLAY "ID: " id. Accessing the populated field. 'id' now contains the value 5 from the JSON.
14
DISPLAY "Active: " active. Accessing the boolean value. Note that JSON booleans might need special handling or mapping to alphanumeric fields in some COBOL implementations.