我遵循使用的格式这回答了如何为文档中的 json 列表着色,但我注意到在字符串列表和数字列表中,只有第一个元素被正确着色。有没有办法可以更改定义来解决这个问题?
修改后使用失败项的示例:
\documentclass{article}
%\usepackage[T1]{fontenc}
\usepackage{xcolor}
\usepackage{listings}
\newcommand\jsonkey{\color{purple}}
\newcommand\jsonvalue{\color{cyan}}
\newcommand\jsonnumber{\color{orange}}
% switch used as state variable
\makeatletter
\newif\ifisvalue@json
\lstdefinelanguage{json}{
tabsize = 4,
showstringspaces = false,
keywords = {false,true},
alsoletter = 0123456789.,
morestring = [s]{"}{"},
stringstyle = \jsonkey\ifisvalue@json\jsonvalue\fi,
MoreSelectCharTable = \lst@DefSaveDef{`:}\colon@json{\enterMode@json},
MoreSelectCharTable = \lst@DefSaveDef{`,}\comma@json{\exitMode@json{\comma@json}},
MoreSelectCharTable = \lst@DefSaveDef{`\{}\bracket@json{\exitMode@json{\bracket@json}},
basicstyle = \ttfamily
}
% enter "value" mode after encountering a colon
\newcommand\enterMode@json{%
\colon@json%
\ifnum\lst@mode=\lst@Pmode%
\global\isvalue@jsontrue%
\fi
}
% leave "value" mode: either we hit a comma, or the value is a nested object
\newcommand\exitMode@json[1]{#1\global\isvalue@jsonfalse}
\lst@AddToHook{Output}{%
\ifisvalue@json%
\ifnum\lst@mode=\lst@Pmode%
\def\lst@thestyle{\jsonnumber}%
\fi
\fi
%override by keyword style if a keyword is detected!
\lsthk@DetectKeywords%
}
\makeatother
\begin{document}
\section{A complex example}
\begin{lstlisting}[language=json]
{
"string": [
“Test1”,
“Test2”,
],
"numbers": [0, …, 10],
"name":
"test"
}
\end{lstlisting}
\end{document}
答案1
您可以使用minted
:listings
\documentclass{article}
\usepackage{xcolor}
\usepackage{minted}
\begin{document}
\section{A complex example}
\usemintedstyle{friendly}
\inputminted{json}{test.json}
\end{document}
其中test.json
包含:
{
"string": [
"Test1",
"Test2",
],
"numbers": [0, …, 10],
"name":
"test"
}
您需要使用 调用 latex --shell-escape
。输出如下所示:
此示例使用样式呈现friendly
,您可以在此处浏览和测试其他可用样式:https://pygments.org/demo/