Json 파일 기반 동적 테이블

Json 파일 기반 동적 테이블

디스크의 파일에 JSON으로 저장된 2차원 배열을 기반으로 하는 동적 테이블을 추가하려고 합니다. 파일은 웹 서비스에서 가져오고 문서는 이를 기반으로 동적으로 생성되므로 파일을 제어할 수 없습니다.

파일의 샘플은 다음과 같습니다.

[
    {"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전체 파일을 읽는 반면*l 는 한 줄씩 읽는 데 사용됩니다.루아 매뉴얼.

관련 정보