DEV Community

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

Posted on • Edited on

4 2

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!

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs