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 the objects as files in a file system is a simple and convenient method for storing basic information such as configuration data. 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.

Serializing objects using Lua is very easy. Any Lua object can be converted to JSON by calling ba.json.encode(object), where object is a Lua table.

Example:

local myconf={
   ipaddr="192.168.1.10",
   mask="255.255.255.0",
   defaultgw="192.168.1.1",
   adminpassword="qwerty",
   maxusers=10
}
local fp = ba.openio("vm"):open("myconf.json", "w")
if fp then
   fp:write(ba.json.encode(myconf))
   fp:close()
end

In the above 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 myconf
local fp = ba.openio("vm"):open("myconf.json", "r")
if fp then
   myconf=ba.json.decode(fp:read("*a"))
   fp:close()
end

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.