BudiBadu Logo
Samplebadu

COBOL by Example: JSON Generation

COBOL 2002

Generating JSON from COBOL data using JSON GENERATE statement, serializing group items into JSON objects automatically, ensuring proper type conversion for numbers and strings, supporting REST API integration and microservices, and using NAME OF phrase for custom field mapping.

Code

       IDENTIFICATION DIVISION.
       PROGRAM-ID. JSON-GEN.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  PRODUCT.
           05 SKU      PIC X(5) VALUE "A-100".
           05 PRICE    PIC 99V99 VALUE 19.99.
       01  JSON-OUT    PIC X(100).
       
       PROCEDURE DIVISION.
           JSON GENERATE JSON-OUT FROM PRODUCT.
           DISPLAY JSON-OUT.
           STOP RUN.

Explanation

Similar to XML, JSON GENERATE converts COBOL data structures into JSON strings. This is essential for modern REST APIs and microservices integration, allowing COBOL backends to serve data directly to web and mobile frontends.

The resulting JSON will look like {"PRODUCT": {"SKU": "A-100", "PRICE": 19.99}}. You can suppress the top-level name or customize field names using the NAME OF phrase. The system handles data type conversions, ensuring numbers appear as numbers and strings as strings (with quotes).

Like XML generation, you should always handle potential exceptions. If the output buffer is too small to hold the generated JSON, an exception condition is raised, which you can catch with ON EXCEPTION.

Code Breakdown

12
JSON GENERATE JSON-OUT. Starts the serialization process. The result goes into JSON-OUT.
12
FROM PRODUCT. The source data. The hierarchy of the PRODUCT group item is preserved in the JSON object.
13
DISPLAY JSON-OUT. Prints the resulting JSON string.