Last active
February 12, 2018 09:31
-
-
Save luyilin/b024a635c3fb5521764151d93342b7b1 to your computer and use it in GitHub Desktop.
json format && highlight
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
// Format json and highlight it as well. | |
// Now you can use the package https://github.com/luyilin/json-format-highlight directly! :D | |
// default colors of key and types of value | |
const defaultColors = { | |
keyColor: 'dimgray', | |
numberColor: 'lightskyblue', | |
stringColor: 'lightcoral', | |
trueColor: 'lightseagreen', | |
falseColor: '#f66578', | |
nullColor: 'cornflowerblue' | |
} | |
function formatHighlight(json, colorOptions = {}) { | |
if (!json) return | |
if (typeof json !== 'string') { | |
json = JSON.stringify(json, null, 2) | |
} | |
let colors = Object.assign({}, defaultColors, colorOptions) | |
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, (match) => { | |
let color = colors.numberColor | |
if (/^"/.test(match)) { | |
color = /:$/.test(match) | |
? colors.keyColor | |
: colors.stringColor | |
} else { | |
color = /true/.test(match) | |
? colors.trueColor | |
: /false/.test(match) | |
? colors.falseColor | |
: /null/.test(match) | |
? colors.nullColor | |
: color | |
} | |
return `<span style="color: ${color}">${match}</span>` | |
}) | |
} | |
// usage e.g. | |
formatHighlight(json, {falseColor: 'red'}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment