5

I am using the latex beamer and trying to get the true value of the flag key in the JSON format red too but I am just getting it black as shown in the screen shot below. How can I get it red too?

enter image description here

Code:

\documentclass[xcolor=dvipsnames]{beamer}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[english]{babel}
\usetheme{Antibes}
\usecolortheme[named=Maroon]{structure} 
\setbeamercovered{transparent}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{xcolor}
\usepackage{listings}

\newcommand\JSONnumbervaluestyle{\color{red}}
\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}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


\title{Test}
\author{Alex XYZ}
\institute{University XYZ}
\date{20.01.16}



\begin{document}
\beamertemplatenavigationsymbolsempty

\begin{frame}
\titlepage
\end{frame}

\begin{frame}[fragile]{Service Provider - Request and Response}

\begin{lstlisting}[style=json]
{
  "mac": "10:B5:S3:06:C6:E9",
  "route":0,
  "latitude":53.834588, 
  "longitude":10.704048,  
  "time":"12.09.2015 13:45:00",
  "speed":3,
  "direction":"",
  "flag": "true"
}  
\end{lstlisting}

\end{frame}

\end{document}
  • Thanks for the code. This is really useful. A hint for all others visiting this page trying to find JSON styling for Latex: if you replace the line 'stringstyle = \ifcolonfoundonthisline\JSONstringvaluestyle\fi,' with 'stringstyle = \color{blue}\ifcolonfoundonthisline\JSONstringvaluestyle\fi,' (replace blue by whatever color you prefer), you can also color the JSON keys. – Hubert Grzeskowiak May 13 '16 at 12:40
7

If you delete this line

  keywords            = {false,true},

the string "true" is treated as a string and goes red

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.