Ask Reuben

Read/Write Variables From/To A File

How can I quickly write a variable to a file?

How can I populate a variable with the contents of a file?

Occasionally you have a requirement to read or write a complex variable from or to a file.  This could be during debugging, you want to read a complex variable or perhaps compare it to an earlier value to find the difference.  This could be during QA where you want to populate some variables with some known values or again compare the difference with an earlier saved result.

There is a handy little technique you can use that involves JSON and the TEXT datatype to read/write any given variable from/to a file.

This does not need base.Channel to read/write file,  nor do you need to know anything about the underlying variable.  As long as the variable, or if it is an array or record, its members are composed of primitive data-types i.e a STRING, not base.StringBuffer

To write any variable to file, you can do the following …

DEFINE t TEXT
...
LOCATE t IN MEMORY
LET t = util.JSON.stringify(variable-name)
CALL t.writeFile(file-name)

That is use the stringify JSON method to express the variable as a JSON string, and then use the TEXT writeFile method to save that string as a file.

To read from file, and populate a variable you can do the opposite …

DEFINE t TEXT
...
LOCATE t IN MEMORY
CALL t.readFile(file-name)
CALL util.JSON.parse(t, variable-name)

That is use the TEXT readFile method to read a file into a TEXT variable, and then the JSON parse method to parse the JSON string into a variable structure.

Both use the fact that 4gl runtime will convert TEXT to STRING and vice versa as per the conversion reference

You could do something similar with XML instead of JSON that would not need the intermediate TEXT variable.   I like the robustness of the JSON parse method and the simplicity of the file.