Example 1: Reading a JSON file

This program reads JSON data from customers.json, parses the line to fill the program variables, coverts the program variable back to JSON and writes a formatted JSON string to the standard output.

We assume that the source file contains the list of customers in a single line that can be read with base.Channel.readLine():

IMPORT util
MAIN
  DEFINE custlist DYNAMIC ARRAY OF RECORD
            num INTEGER,
            name VARCHAR(40)
         END RECORD
  DEFINE ch base.Channel
  LET ch = base.Channel.create()
  CALL ch.openFile("customers.json","r")
  CALL util.JSON.parse( ch.readLine(), custlist )
  DISPLAY custlist.getLength()
  DISPLAY util.JSON.format( util.JSON.stringify(custlist) )
  CALL ch.close()
END MAIN

-- customers.json file:
[ {"num":823, "name":"Mark Renbing" }, {"num":234, "name":"Clark Gambler" } ]

Note that the JSON file does not contain the name of the dynamic array (custlist), but starts directly with the JSON array in [ ] square braces.