Skip to content

Instantly share code, notes, and snippets.

@luyilin
Last active February 12, 2018 09:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luyilin/b024a635c3fb5521764151d93342b7b1 to your computer and use it in GitHub Desktop.
Save luyilin/b024a635c3fb5521764151d93342b7b1 to your computer and use it in GitHub Desktop.
json format && highlight
// 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