ConTeXt and Lua programming/Processing JSON

Unofficial ConTeXt Wiki mirror

Last modified: 2025-10-12

Without Lua

You can load JSON files in ConTeXt with the included json module:

\usemodule[json]
\loadtable[namespace][filename]
\tablefield{namespace}{fieldname}
\tablefielddefault{namespace}{fieldname}{default value}
\tablelength{namespace}{fieldname}
\tableformatted{namespace}{fieldname}{format}

The JSON structure from the file filename is converted to a Lua table with the internal name namespace.

You can access single or nested keys via fieldname, e.g. "title" or "author.name".

format in \tableformatted refers to a Lua string.format, same as C’s sprintf. Lua manual

With Lua

The TeX approach above usually only makes sense for JSON files with a simple structure. Otherwise it’s much easier to use Lua code:

local data = utilities.json.load("filename.json")

Now the whole structure from filename is accessible in the Lua table data. No need to load the module, that only enables the ConTeXt commands.

You can also save a Lua table as JSON:

io.savedata("filename.json", utilities.json.tojson(data))

Example

Here’s a complete example (by Hans Hagen on the mailing list 2025-10-12):

\usemodule[json]

\starttext

\startluacode
    local t = {
        a = {
            b = {
                c = "here",
            }
        },
        b = "there",
        d = { 1, 2, 3, 4 },
    }

    utilities.tablestore.load("crap",t)

    io.savedata("oeps.json",utilities.json.tojson(t))
\stopluacode

\tablefield {crap}{a.b.c}
\tablefield {crap}{b}
\tablelength{crap}{d}

\loadtable[whatever][oeps.json]

\tablefield {whatever}{a.b.c}
\tablefield {whatever}{b}
\tablelength{whatever}{d}

\stoptext