How can I highlight JSON string values but not attributes?
A MWE is really needed here, so what follows is a bit of a shot in the dark...
Edit: now you can specify a distinct style for numerical JSON values.
\documentclass{article}
%\usepackage[T1]{fontenc}
%\usepackage[scaled=0.85]{beramono}
\usepackage{xcolor}
\usepackage{listings}
\newcommand\JSONnumbervaluestyle{\color{blue}}
\newcommand\JSONstringvaluestyle{\color{red}}
% switch used as state variable
\newif\ifcolonfoundonthisline
\makeatletter
\lstdefinestyle{json}
{
showstringspaces = false,
keywords = {false,true},
alsoletter = 0123456789.,
morestring = [s]{"}{"},
stringstyle = \ifcolonfoundonthisline\JSONstringvaluestyle\fi,
MoreSelectCharTable =%
\lst@DefSaveDef{`:}\colon@json{\processColon@json},
basicstyle = \ttfamily,
keywordstyle = \ttfamily\bfseries,
}
% flip the switch if a colon is found in Pmode
\newcommand\processColon@json{%
\colon@json%
\ifnum\lst@mode=\lst@Pmode%
\global\colonfoundonthislinetrue%
\fi
}
\lst@AddToHook{Output}{%
\ifcolonfoundonthisline%
\ifnum\lst@mode=\lst@Pmode%
\def\lst@thestyle{\JSONnumbervaluestyle}%
\fi
\fi
%override by keyword style if a keyword is detected!
\lsthk@DetectKeywords%
}
% reset the switch at the end of line
\lst@AddToHook{EOL}%
{\global\colonfoundonthislinefalse}
\makeatother
\begin{document}
\section{A simple example}
\begin{lstlisting}[style=json]
example
{
"name" : "alan",
"alias" : "nala",
}
\end{lstlisting}
\section{A more complicated example}
\begin{lstlisting}[style=json]
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"height_cm": 167.6,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
}
]
}
\end{lstlisting}
\end{document}