(Lualatex)如何循环遍历 JSON 对象数组

(Lualatex)如何循环遍历 JSON 对象数组

如何循环下面MP的 JSON 并将对象的键/值打印到表中?

{
"MP": [
      {
        "A": "A1"
      },
      {
        "B": "B1"
      },
      {
        "C": "C1"
      }
    ]
}

在此处输入图片描述

这是我的 Lua 代码:

\documentclass{article}
\usepackage{luacode}
\usepackage{datatool}
\DTLsetseparator{,}% Set the separator between the columns.
\usepackage{longtable}
\usepackage{tabularx}
\usepackage{amsmath}

\usepackage{hhline}
\usepackage{multicol}
\usepackage{multirow}
\usepackage{booktabs}
\usepackage{makecell}
\usepackage{color, colortbl}
\usepackage[table]{xcolor}

\usepackage[document]{ragged2e}
\usepackage[nohead,paperheight=11.0in,paperwidth=8.5in,left=0.5in,right=0.5in,top=0.5in,bottom=1.0in]{geometry}

%%%% Font %%%%
\usepackage{fontspec}
\usepackage{xparse}
\usepackage{etoolbox}
\usepackage{array}
\usepackage{luacode}
\usepackage{xcolor}
\begin{document}
\newcolumntype{L}{|>{\raggedright\arraybackslash\bfseries}X|X}
\catcode10=9\

\begin{luacode*}
local json = require("json")
local file = io.open("data.json")
tab = json.parse(file:read("*all"))

file:close()

tex.sprint(
    [[\begin{table}[ht!]
    \centering
    \begin{tabularx}{\textwidth}{@{} LL @{}}
    \rowcolor{lightgray!50}
    \hline]])
    for k, v in ipairs(tab["MP"]) do
        tex.sprint(
        [[\textbf]],
        k, [[& ]],
        v, [[\\]],
        [[\hhline{--}]])
    end  
tex.sprint(
    [[\hhline{--}
    \end{tabularx}
    \end{table}]])

\end{luacode*}
\end{document}

解析 JSON 的 json.lua 文件来自http://regex.info/blog/lua/json

相关内容