3

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"}
];
  • What should the output look like? – Werner Mar 24 '16 at 20:22
  • Just a normal \begin{tabular}{ l | c || r } with \hline, but I'll figure out the layout easily once it's in tex format. Thanks @Werner – Ovi Mar 24 '16 at 20:29
5

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

  • Nice. Not being familiar with Lua syntax, what does *a mean? – daleif Mar 26 '16 at 18:44
  • @daleif It means, that the whole file will be read. – Benjamin Mar 26 '16 at 21:25
  • What does Lua do normally? A line at a time (with a programming term I've forgotten the name of) – daleif Mar 26 '16 at 21:42
  • @daleif Well, I wouldn't say Lua "normally" does it, but you can also read a file line by line (*l or *L), yes. Or you can read a fixed number of bytes if you want to. Just have a look at the manual: lua.org/manual/5.2/manual.html#6.8 – Benjamin Mar 26 '16 at 21:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.