Skip to content

Instantly share code, notes, and snippets.

@flaksp
Last active August 30, 2025 15:08
Show Gist options
  • Save flaksp/282f0d47f441c54b213c03463c062f89 to your computer and use it in GitHub Desktop.
Save flaksp/282f0d47f441c54b213c03463c062f89 to your computer and use it in GitHub Desktop.
JSON Formatter Userscript

Userscript for Formatting JSON

A simple userscript that formats JSON by using a JSON.stringify(data, null, 2) function. It only runs if a page has proper Content-Type response header, e.g. application/json. It does not support syntax highlighting. It also sorts JSON keys alphabetically.

It's compatible with Userscripts, Tampermonkey, and other similar apps.

// ==UserScript==
// @name JSON Formatter
// @description Formats JSON if it's application/json
// @match *://*/*
// ==/UserScript==
const isObject = (value) =>
typeof value === "object" && !Array.isArray(value) && value !== null;
const sortObjectKeys = (value) => {
if (isObject(value)) {
return Object.keys(value)
.sort()
.reduce((result, key) => {
result[key] = sortObjectKeys(value[key]);
return result;
}, {});
} else if (Array.isArray(value)) {
return value.map(sortObjectKeys);
} else {
return value;
}
};
const contentType = document.contentType;
const [type, subtype] = contentType.split("/", 2);
if (
type === "application" &&
(subtype === "json" || subtype.endsWith("+json"))
) {
let content = JSON.parse(document.body.textContent);
content = sortObjectKeys(content);
const pre = document.createElement("pre");
pre.style.fontFamily =
"Menlo, Consolas, Monaco, Liberation Mono, Lucida Console, monospace";
const formattedJson = JSON.stringify(content, null, 2);
pre.appendChild(document.createTextNode(formattedJson));
document.body.innerHTML = "";
document.body.appendChild(pre);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment