LaTeX: Typeset Programming Source Code & Wordwrap

I had to display JSON data on my report.

I had problem while writing it as a plain text.
– I need to make the json data distinguished from other report text.
– I also had problems with the underscores used in my json data. LaTeX will throw an error for underscores in text.

LaTeX’s Listings Package was helpful to solve this issue.

This package typesets programming codes making the source code readable. Key­words, com­ments and strings can be type­set us­ing dif­fer­ent styles (de­fault is bold for key­words, italic for com­ments and no spe­cial style for strings). Sup­port for hy­per­ref is also pro­vided.

At first, we need to use the package in preamble: \usep­a­ck­age{list­ings}
Then we can provide necessary settings, like programming language to be used: \lst­set{lan­guage=Python}
Then, in the document body, we can use environment lstlist­ing for inline code.

Here is the sample LaTeX code that I used to display my JSON data:


\documentclass{report}

\usepackage{listings}
\lstset{
basicstyle=\ttfamily,
columns=flexible,
breaklines=true
}

\begin{document}

\chapter{Introduction}

\section{JSON data}
\begin{lstlisting}
{"votes": {"funny": 0, "useful": 0, "cool": 0}, "user_id": "111", "review_id": "222", "stars": 5, "date": "2011-05-10", "text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ac aliquam tellus. Nunc cursus lorem in pellentesque ullamcorper. Proin tempus semper faucibus. Maecenas ac gravida velit, vel laoreet magna. Curabitur efficitur quis orci sit amet congue. Nunc sem enim, pretium a mi id, pellentesque cursus tellus. Fusce fringilla rutrum turpis at sagittis.", "type": "review", "business_id": "333"}

{"votes": {"funny": 0, "useful": 0, "cool": 0}, "user_id": "222", "review_id": "333", "stars": 4, "date": "2012-05-08", "text": "Maecenas a efficitur quam, a condimentum dolor. Nulla facilisi. Ut at gravida dolor. Nullam finibus eros id dolor mollis gravida. Nulla eu leo ornare erat cursus congue vel eget leo. Donec vulputate congue urna, vel pretium magna vulputate id. Ut dictum mi non nisi dictum fermentum. Morbi sed laoreet tortor. Aenean fermentum pulvinar leo, eget consequat leo. Morbi nec lacus vitae eros elementum accumsan quis ut ligula. Proin vestibulum arcu sit amet nibh aliquet, in aliquet tellus tempor.", "type": "review", "business_id": "444"}
\end{lstlisting}

\newpage

\section{Java code}

\begin{lstlisting}
/* HelloWorld.java
 */

public class HelloWorld
{
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}
\end{lstlisting}

\end{document}

Here is the output of the above code:

Hope this helps. Thanks.