Created
February 10, 2019 19:36
-
-
Save dperrymorrow/5fd782c87ed79286cde3c2d430d903e1 to your computer and use it in GitHub Desktop.
syntax highlight json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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