6

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.

4
  • Could you give a minimum working example of what you've tried? This question doesn't make sense in the context of TeX yet.
    – Ryan
    Nov 1, 2016 at 7:17
  • Related: tex.stackexchange.com/questions/152829/…
    – Marijn
    Nov 1, 2016 at 8:42
  • @Ryan: sorry just updated it in the question.
    – aries
    Nov 1, 2016 at 11:23
  • For complex highlighting requirements, minted might be worth to consider.
    – corvus_192
    Jul 23, 2020 at 11:41

1 Answer 1

8

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.

4
  • 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 2, 2016 at 1:02
  • 1
    It is hard to guarantee anything: 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 2, 2016 at 1:20
  • 2
    (And if you take a look at how 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 2, 2016 at 1: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 2, 2016 at 1:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .