TransWikia.com

(Lualatex)How to loop over an array of JSON objects

TeX - LaTeX Asked by 24suns on July 20, 2021

How do I loop over MP in the JSON below and print the key/value of the objects into a table?

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

enter image description here

This is my Lua code:

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}{|>{raggedrightarraybackslashbfseries}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.lua file that parses the JSON is from http://regex.info/blog/lua/json

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP