CSV parsing

Reading CSV

A CSV line is a record with comma delimiters. UNSTRING splits it into fields, and TALLYING counts how many arrived, which catches short lines before they hit the file:

UNSTRING WS-LINE DELIMITED BY "," INTO WS-NAME WS-DEPT WS-SALARY TALLYING WS-FIELDS. IF WS-FIELDS NOT = 3 DISPLAY "Bad row" END-IF.

Quoted fields

UNSTRING does not understand quoted commas. If a field can contain commas inside quotes, parse it with a paragraph that walks the line character by character, or use JSON PARSE when the source can emit JSON instead.

Writing CSV

STRING joins fields back into a line. Put the delimiter as its own element, and watch for trailing spaces in fixed-length fields: a PIC X(30) name pads with spaces that end up inside the CSV cell:

STRING WS-NAME "," WS-DEPT "," WS-SALARY DELIMITED BY SIZE INTO WS-LINE.

The code on this page was run with GnuCOBOL 3.2.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev