Overview
What Pretty JSON does
Validates JSON and formats it with two-space indentation without rewriting large numeric literals or duplicate keys.
| Category | Developer Tools |
|---|---|
| Action type | JavaScript |
| Result | Replace or copy text |
| Internet | Not required |
Example
Action and outcome
| Action | Outcome |
|---|---|
| Pretty JSONSelected text: {"name":"ActionClip","enabled":true} | { "name": "ActionClip", "enabled": true } |
Workflow
Use Pretty JSON
Follow these steps to format selected JSON with readable indentation with ActionClip.
- Select the text you want to use.
- Choose Pretty JSON from ActionClip.
- Review the result, then replace the selection or copy the new text.
Before you add it
Requirements and privacy
- Before you start: No setup required.
- Your selected text: Runs locally in ActionClip’s JavaScript sandbox. Selected text does not leave your Mac.
Inspect before installing
Action configuration
The definition below is included so you can inspect how the action works before downloading it.
JavaScript definition
function run(selected_text) {
const input = selected_text.trim();
try {
JSON.parse(input);
} catch (error) {
throw new Error("Invalid JSON: " + error.message);
}
let output = "";
let depth = 0;
let inString = false;
let escaped = false;
const indent = () => " ".repeat(depth);
const nextNonWhitespace = (start) => {
for (let index = start; index < input.length; index += 1) {
if (!/\s/.test(input[index])) return input[index];
}
return "";
};
for (let index = 0; index < input.length; index += 1) {
const character = input[index];
if (inString) {
output += character;
if (escaped) escaped = false;
else if (character === "\\") escaped = true;
else if (character === '"') inString = false;
continue;
}
if (character === '"') {
inString = true;
output += character;
} else if (character === "{" || character === "[") {
output += character;
const closing = character === "{" ? "}" : "]";
if (nextNonWhitespace(index + 1) !== closing) {
depth += 1;
output += "\n" + indent();
}
} else if (character === "}" || character === "]") {
const opening = character === "}" ? "{" : "[";
let previous = output.length - 1;
while (previous >= 0 && /\s/.test(output[previous])) previous -= 1;
if (previous >= 0 && output[previous] !== opening) {
depth = Math.max(0, depth - 1);
output = output.replace(/\s+$/, "") + "\n" + indent();
}
output += character;
} else if (character === ",") {
output += ",\n" + indent();
} else if (character === ":") {
output += ": ";
} else if (!/\s/.test(character)) {
output += character;
}
}
return output;
}