[Tex/LaTex] Dynamic Table based on Json File

external filesjsontables

I'm trying to add in a dynamic table based on a two-dimensional array that is stored as JSON in a file on the disk. I've got no control of the file, as it gets pulled in from a web-service and documents are dynamically created based on it.

As a sample of the file, it looks something like this:

[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter","lastName": "Jones"}
];

Best Answer

This is a good example where LuaTeX is very useful. You can easily load and parse the json file with it and write the data into a table. Here is an example:

\begin{filecontents*}{data.json}
[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
];
\end{filecontents*}
\documentclass{article}
\usepackage{luacode}
\begin{document}
\begin{luacode}
require("lualibs.lua")
local file = io.open('data.json')
local jsonstring = file:read('*a')
file.close()
local jsondata =  utilities.json.tolua(jsonstring)
tex.print('\\begin{tabular}{cc}')
tex.print('\\hline\\textbf{Firstname} & \\textbf{Lastname} \\\\\\hline')
for key, value in pairs(jsondata) do
    tex.print(value["firstName"] .. ' & ' .. value["lastName"] .. '\\\\')
end
tex.print('\\hline\\end{tabular}')
\end{luacode}
\end{document}

Output:

table