[Tex/LaTex] How to assign variables from a [json|yaml|toml] file

automationjsonmarkup

I have two Latex files for a weekly document I create. template.tex contains a large list of variables that get changed each week:

\newcommand{\var}{foo}
\newcommand{\othervar}{bar}

Then the template.tex imports document.tex which is the actual document with each variable in the right spot.

I would like to update this with Python. Currently I have a Python script that finds the appropriate variables in a Google Docs spreadsheet and saves them as a toml file. I would like Latex to read that toml (or json or yaml it doesn't matter the format to me) and then assign the values of those variables based on it.

Best Answer

Space separated values are simpler to parse than JSON, for example

enter image description here

From a text file vars.txt

var foo
othervar bar
zzz 42

and a tex file

\documentclass{article}

\newread\varsfile
\def\assignvar#1 #2\relax{\expandafter\gdef\csname #1\endcsname{#2}}
\openin\varsfile=vars.txt
{\endlinechar=-1
\loop
\ifeof\varsfile\else
\read\varsfile to \tmp
\ifx\tmp\empty\else
\expandafter\assignvar\tmp\relax
\fi
\repeat
}
\closein\varsfile

\begin{document}


var is \var\ and zzz is \zzz, othevar is \othervar.

\end{document}
Related Question