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, "<")
.replace(/>/g, ">");
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>";
}
);
}
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;
}
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>
);
}
Happy Coding, Thanks!
Top comments (3)
simply & nice
I am glad you like it!
just more minified the same css+js, but with ability JSON stringify input argument: