4

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.

  • 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 '16 at 7:17
  • Related: tex.stackexchange.com/questions/152829/… – Marijn Nov 1 '16 at 8:42
  • @Ryan: sorry just updated it in the question. – aries Nov 1 '16 at 11:23
5

There is a trick way: hight all strings except those following a semicolon.

\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 aspects dealing with attributes and values by yourself.

  • 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 '16 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 '16 at 1:20
  • 1
    (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 '16 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 '16 at 1:38

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.