Storing Persistent Data By Using JSON

JavaScript Object Notation, or JSON for short, is a lightweight computer data interchange format.

Serializing Lua objects to JSON and storing them as files in a filesystem is a simple and convenient way to keep basic persistent data such as configuration settings. Using JSON as a "mini-database" may be of particular interest to firmware developers as a device may not have enough memory to run a database such as SQLite.

APIs:

Example:

Use ba.json.encode() to serialize a Lua table containing JSON-compatible values. This does not preserve arbitrary Lua objects: unsupported values and recursive references become JSON null. See the encoder reference for table-to-object and table-to-array conversion rules.

In these examples, io is a writable BAS I/O interface, not the standard Lua io library. The examples use assert() to stop on a reported error, after closing any opened file.

local myconf={
   ipaddr="192.168.1.10",
   mask="255.255.255.0",
   defaultgw="192.168.1.1",
   adminpassword="qwerty",
   maxusers=10
}
-- Encode before opening the file so an encoding failure does not truncate it.
local data = assert(ba.json.encode(myconf))
local fp = assert(io:open("myconf.json", "w"))
local ok, err = fp:write(data)
local closed, closeerr = fp:close() -- Close even when writing fails.
assert(ok, err)
assert(closed, closeerr)

In this example, a Lua table is created with some configuration parameters. The table is converted to JSON and saved as "myconf.json". The saved configuration data can be restored as follows:

local fp = assert(io:open("myconf.json", "r"))
local data, err = fp:read() -- Read all bytes.
local closed, closeerr = fp:close() -- Release the file before decoding.
assert(data, err)
assert(closed, closeerr)
local myconf = assert(ba.json.decode(data))

Function ba.json.decode is internally using the JSON Parser Class. The JSON Parser has many uses besides being used for parsing saved configuration data. See the JSON C implementation for more information.