Skip to content

Instantly share code, notes, and snippets.

@hogashi
Last active July 6, 2018 15:20
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 hogashi/fa02f23e7df7de08ec66488d98145b45 to your computer and use it in GitHub Desktop.
Save hogashi/fa02f23e7df7de08ec66488d98145b45 to your computer and use it in GitHub Desktop.
jsonを整形するブックマークレット
javascript:(
() => {
const doneId = 'json-formatter-hogashi';
if (document.querySelector(`#${doneId}`)) {
return;
}
/* EDIT HERE: `elem` is the element which has one-lined-JSON text */
const elem = document.querySelector('pre');
let str = elem.innerHTML,
formatted = '',
cursor = 0,
bigp = 0,
midp = 0;
const newLineWithSpace = num => {
let nlsp = '\n';
for (let i = 0; i < num; i++) {
nlsp += ' ';
}
return nlsp;
};
const length = str.length;
while (cursor < length) {
switch (str[cursor]) {
case '{':
formatted += '{' + newLineWithSpace((bigp + ++midp) * 2);
cursor++;
break;
case '[':
formatted += '[' + newLineWithSpace((++bigp + midp) * 2);
cursor++;
break;
case '"':
const [quoted] = str.slice(cursor).match(/"(?:\\\\|((?<!\\)\\(?!("|\\)))|[^\\"]|\\")*?"/);
formatted += quoted;
cursor += quoted.length;
break;
case ',':
formatted += ',' + newLineWithSpace((bigp + midp) * 2);
cursor++;
break;
case ':':
formatted += ': ';
cursor++;
break;
case '}':
formatted += newLineWithSpace((bigp + --midp) * 2) + '}';
cursor++;
break;
case ']':
formatted += newLineWithSpace((--bigp + midp) * 2) + ']';
cursor++;
break;
default:
formatted += str[cursor];
cursor++;
break;
}
}
elem.innerHTML = formatted;
document.querySelector('body').insertAdjacentHTML('beforeend', `<div id="${doneId}" style="display: none;"></div>`)
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment