[Tex/LaTex] Load fields from JSON file using LuaLatex

jsonluacodeluatexparsing

I want to load a lot of numbers in my document from a single JSON file that is returned from a simulation. To do that I so far followed this stackexchange answer but for multiple values I would have to load the JSON file several times throughout the documents (I am new to LuaLatex so maybe I am missing something essential). What I want is something like this:

\documentclass{article}
\usepackage{luacode}

\begin{document}

\begin{luacode}
function read(file)
    local handler = io.open(file, "rb")
    local content = handler:read("*all")
    handler:close()
    return content
end
JSON = (loadfile "JSON.lua")()
local table = JSON:decode(read("recipes.json"))
\end{luacode}

The fat content of the recipe \directlua{tex.print(table['recipe']
['title'])} is \directlua{tex.print(table['recipe']
['fat'])}.

\end{document}

What is the cleanest way to achieve that?

Best Answer

I found the answer: in the example above the relevant variable (table) is defined as local. That's why it is not accessible in subsequent lua calls. The solution is thus

\documentclass{article}
\usepackage{luacode}

\begin{document}

% load json file
\begin{luacode}
function read(file)
    local handler = io.open(file, "rb")
    local content = handler:read("*all")
    handler:close()
    return content
end
JSON = (loadfile "JSON.lua")()
table = JSON:decode(read("recipes.json"))
\end{luacode}

The fat content of the recipe \directlua{tex.print(table['recipe']
['title'])} is \directlua{tex.print(table['recipe']
['fat'])}.

\end{document}