Serialization with JSON
As part of the of the MoonSharp libraries that are utilized within BobCAD-CAM products, there also exists modules within our Lua scripts for reading and writing JSON format files which can be used for multiple purposes. The functions shown below can be utilized for converting a Lua table to a JSON file as well as read a JSON file and convert to a Lua table.
One common purpose is that perhaps you want your plug-in to remember the settings that were chosen by the user even after the application has been closed, so you can load them back in the state the user set them.
Overview
MoonSharp offers a json module which converts between JSON scripts and Lua Tables.
A major point is that JSON can represent nulls while tables cannot contain a nil value. In order to overcome this, a special value is used to represent nulls read from a JSON file and the function json.isNull(val) can be used to check for this special value. The same value (generated by json.null()) can be used in tables which will translated to JSON to represent explicit nulls.
The following 4 functions exist to handle your JSON file interactions:
- json.parse(jsonString) - Returns a table with the contents of the specified json string.
- json.serialize(table) - Returns a json string with the contents of the specified table.
- json.isNull(val) - Returns true if the value specified is a null read from a json
- json.null() - Returns a special value which is a representation of a null in a json