基於Json檔案的動態表

基於Json檔案的動態表

我正在嘗試添加基於二維數組的動態表,該數組以 JSON 形式存儲在磁碟上的文件中。我無法控制該文件,因為它是從網路服務中提取的,並且文件是基於它動態創建的。

作為文件的範例,它看起來像這樣:

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

答案1

這是 LuaTeX 非常有用的一個很好的例子。您可以使用它輕鬆載入和解析 json 檔案並將資料寫入表中。這是一個例子:

\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}

輸出:

桌子


注意:lua 中*a讀取整個文件,而 while 則*l用於逐行讀取等。lua手冊

相關內容