TransWikia.com

Simple coloring of json attributes

TeX - LaTeX Asked on December 10, 2021

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.

One Answer

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.

Answered by Symbol 1 on December 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP