Created
December 29, 2017 03:11
-
-
Save lihsai0/24f77a8f429e2f04f97e103eb9e93cc2 to your computer and use it in GitHub Desktop.
[Utils] Useful codes #utils
This file contains hidden or 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
function formatJson (json, options) { | |
let reg = null; | |
let formatted = ''; | |
let pad = 0; | |
let PADDING = ' '; | |
options = options || {}; | |
options.newlineAfterColonIfBeforeBraceOrBracket = options.newlineAfterColonIfBeforeBraceOrBracket === true; | |
options.spaceAfterColon = options.spaceAfterColon === false; | |
if (typeof json !== 'string') { | |
json = JSON.stringify(json); | |
} else { | |
json = JSON.parse(json); | |
json = JSON.stringify(json); | |
} | |
reg = /([{}])/g; | |
json = json.replace(reg, '\r\n$1\r\n'); | |
reg = /([[\]])/g; | |
json = json.replace(reg, '\r\n$1\r\n'); | |
reg = /(,)/g; | |
json = json.replace(reg, '$1\r\n'); | |
reg = /(\r\n\r\n)/g; | |
json = json.replace(reg, '\r\n'); | |
reg = /\r\n,/g; | |
json = json.replace(reg, ','); | |
if (!options.newlineAfterColonIfBeforeBraceOrBracket) { | |
reg = /:\r\n\{/g; | |
json = json.replace(reg, ':{'); | |
reg = /:\r\n\[/g; | |
json = json.replace(reg, ':['); | |
} | |
if (options.spaceAfterColon) { | |
reg = /:/g; | |
json = json.replace(reg, ':'); | |
} | |
(json.split('\r\n')).forEach((node, index) => { | |
let i = 0; | |
let indent = 0; | |
let padding = ''; | |
if (node.match(/\{$/) || node.match(/\[$/)) { | |
indent = 1; | |
} else if (node.match(/\}/) || node.match(/\]/)) { | |
if (pad !== 0) { | |
pad -= 1; | |
} | |
} else { | |
indent = 0; | |
} | |
for (i = 0; i < pad; i++) { | |
padding += PADDING; | |
} | |
formatted += padding + node + '\r\n'; | |
pad += indent; | |
}); | |
return formatted; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment