5

Given a json file in the following format:

"name":"list_of_xy_values",
"data":[[1,2],[2,4],[3,6],[4,3],[5,0]]

I'd like to import data to my document to plot it with tikz/pgfplots, but I'm rather unexperienced with LaTeX.

Is there a library that can import json directly?

If a direct import is not possible, I could easily convert the desired data to a csv file with python. In this case I wonder if and how I can trigger the python script from within latex, so that the data is converted automatically when the LaTeX script compiles and without me needing to call the script manually each time.

Sim Son
  • 264

1 Answers1

7

LuaLaTeX has an integrated JSON parser. With some wrapper code around \pgfplotstableread this can be used to read from a JSON file directly into a pgfplots table.

\begin{filecontents*}{test.json}
{
    "name":"list_of_xy_values",
    "data":[[1,2],[2,4],[3,6],[4,3],[5,0]]
}
\end{filecontents*}

\documentclass{article} \usepackage{pgfplots} \pgfplotsset{compat=newest}

\begin{document}

\expandafter\pgfplotstableread\directlua{ local json = utilities.json.load("test.json") tex.sprint("{\string\r") tex.sprint("x y\string\r") for n, row in ipairs(json.data) do tex.sprint(row[1] .. " " .. row[2] .. "\string\r") end tex.sprint("}") }\loadedtable

\begin{tikzpicture} \begin{axis} \addplot table {\loadedtable}; \end{axis} \end{tikzpicture} \end{document}

enter image description here

Henri Menke
  • 109,596
  • thanks for your answer! is this supposed to be a standalone example? If I try to compile this, I get an error (! Undefined control sequence. l.1 \begin {filecontents*}{test.json}) – Sim Son Dec 28 '20 at 15:04
  • 1
    @Sim Son, you need a recent LaTeX with filecontents in the kernel. Otherwise, add \RequirePackage{filecontents} before the first line – Rmano Dec 28 '20 at 15:30
  • I managed to get the LaTex part to work, but I still get an error from the lua part: [\directlua]:1: attempt to index a nil value (local 'json') – Sim Son Dec 28 '20 at 15:35
  • if I change local json to global json I get the error [\directlua]:1: syntax error near 'json'. – Sim Son Dec 28 '20 at 15:58
  • @SimSon There is no global keyword in Lua. Also your LaTeX seems to be ancient if it doesn't contain filecontents. Better update before attempting to make this example work. – Henri Menke Dec 28 '20 at 16:30
  • I downloaded and installed MiKTeX today and installed that package. Now the example runs if I remove local. Thanks for your help! – Sim Son Dec 28 '20 at 16:42