7

Could someone please explain me how I can color the json attributes for a json string in listing? An example would be great. Thanks.

Example String: {"name1":"attribute1","name2":"attribute2"}. How can I make the string "name1" and "name2" appear blue?

I tried the solution at How can I highlight JSON string values but not attributes? but this highlights the values and not the attributes.

aries
  • 183

1 Answers1

9

There is a trick way: Highlight all strings except those following a colon.

\documentclass{article}
\usepackage{listings,xcolor}
\begin{document}

\lstset{ string=[s]{"}{"}, stringstyle=\color{blue}, comment=[l]{:}, commentstyle=\color{black}, } \begin{lstlisting} { "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}

PS: Internally, the following aspects strings, comments, escape, style, language, keywords, labels, lineshape, frames, emph, index are treat equally. In case you need string/comment for the actual string/comment, you can add an aspect's dealing with attributes and values by yourself.

Stefan Pinnow
  • 29,535
Symbol 1
  • 36,855
  • It doesn't work when the attribute-value pairs are in the same line. In the {"name1":"attribute1","name2":"attribute2"} example, only name1 is highlighted. – aries Nov 02 '16 at 01:02
  • 1
    It is hard to guarantee anything: [tag:listings] is not automata, it cannot remember if this string is before : or after : or the presence of ,. In your example, you might want to try comment=[s]{:\ "}{"} or comment=[s]{:"}{"}. – Symbol 1 Nov 02 '16 at 01:20
  • 2
    (And if you take a look at how [tag:listings] deals with other fancier languages, e.g. C/HTML/..., you will find that most of the time it just brutally collects all possible keywords, and the declaration of the language is pathetically long...) – Symbol 1 Nov 02 '16 at 01:28
  • Your last comment helped. I have same set of attributes for all the json strings. So I added the entire list of attributes to "morekeywords". Thank you. – aries Nov 02 '16 at 01:38