Skip to content

Instantly share code, notes, and snippets.

@dperrymorrow
Created February 10, 2019 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dperrymorrow/5fd782c87ed79286cde3c2d430d903e1 to your computer and use it in GitHub Desktop.
Save dperrymorrow/5fd782c87ed79286cde3c2d430d903e1 to your computer and use it in GitHub Desktop.
syntax highlight json
import { escape } from "lodash";
export default function(str, format = true) {
try {
// ensure that we got valid json here...
const obj = JSON.parse(str);
if (format) str = JSON.stringify(obj, null, 2);
str = _parseObj(obj, str);
// dont wrap with the parent tag till we are done...
return `<span class="json-markup">${str}</span>`;
} catch (err) {
throw err;
}
}
function _wrapWithTag(str, search, classSuffix) {
// make sure we are dealing with a string
search = `${search}`;
// use regex to make sure we are not already inside a tag
return str.replace(
new RegExp(`(${search})(?![^<]*>|[^<>]*</)`),
`<span class="json-markup-${classSuffix}">${escape(search)}</span>`
);
}
function _parseObj(obj, str) {
Object.keys(obj).forEach(key => {
const val = obj[key];
str = _wrapWithTag(str, `"${key}"`, "key");
if (val === null) str = _wrapWithTag(str, val, "null");
else if (typeof val === "object") str = _parseObj(val, str);
else if (typeof val === "string") str = _wrapWithTag(str, `"${val}"`, "string");
else if (typeof val === "boolean") str = _wrapWithTag(str, val, "bool");
else if (typeof val === "number") str = _wrapWithTag(str, val, "number");
});
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment