DEV Community

Cover image for Show JSON As Pretty Print With Syntax Highlighting in React
Gaurav Adhikari
Gaurav Adhikari

Posted on • Updated on

Show JSON As Pretty Print With Syntax Highlighting in React

In this post, we will learn how to show the JSON data as pretty printed, and with colored highlighted syntax in our ReactJS/JS apps.

Coming straight to the utility function below

export function syntaxHighlight(json) {
  if (!json) return ""; //no JSON from response

  json = json
    .replace(/&/g, "&")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;");
  return json.replace(
    /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
    function (match) {
      var cls = "number";
      if (/^"/.test(match)) {
        if (/:$/.test(match)) {
          cls = "key";
        } else {
          cls = "string";
        }
      } else if (/true|false/.test(match)) {
        cls = "boolean";
      } else if (/null/.test(match)) {
        cls = "null";
      }
      return '<span class="' + cls + '">' + match + "</span>";
    }
  );
}
Enter fullscreen mode Exit fullscreen mode

and the CSS

pre {
  outline: 1px solid #ccc;
  padding: 5px;
  margin: 15px;
}
.string {
  color: green;
}
.number {
  color: darkorange;
}
.boolean {
  color: blue;
}
.null {
  color: magenta;
}
.key {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

Now we can use our syntaxHighlight function, just pass it with JSON to prettify and highlight

Example usage in ReactJS app:

import { useEffect, useState } from "react";

import { syntaxHighlight } from "./utils";
import "./styles.css";

export default function App() {
  const [ourJSON, setOurJSON] = useState();

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then((response) => response.json())
      .then((json) => setOurJSON(json));
  }, []);

  return (
    <div>
      <h3 className="header">
        Show JSON As Pretty Print With Syntax Highlighting
      </h3>
      <pre
        dangerouslySetInnerHTML={{
          __html: syntaxHighlight(JSON.stringify(ourJSON, undefined, 4))
        }}
      />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Credit for utility function

Happy Coding, Thanks!

Top comments (3)

Collapse
 
katheesh profile image
кαтнєєѕкυмαɾ

simply & nice

Collapse
 
gauravadhikari1997 profile image
Gaurav Adhikari

I am glad you like it!

Collapse
 
zedemian profile image
Demian Blacksmith • Edited

just more minified the same css+js, but with ability JSON stringify input argument:

.string {color: green} .number {color: darkorange} .boolean {color: blue} .null {color: magenta} .key {color: red}
Enter fullscreen mode Exit fullscreen mode
const highlight = json => (!(json = typeof json !== "string" ? JSON.stringify(json, null, 2) : json)) ? ""
        : json.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(
            /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
            val => '<span class="'+(/^"/.test(val) ? (/:$/.test(val)?"key":"string")
                : (/true|false/.test(val) ? "boolean" : (/null/.test(val)?"null":"number")))+'">'+val+"</span>"
        );
Enter fullscreen mode Exit fullscreen mode