Need help with your JSON?
Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool
Building JSON Formatter Workflows for Alfred & Spotlight
As developers, dealing with JSON data is a daily occurrence. Whether it's API responses, configuration files, or logging, reading unformatted, dense JSON strings can be a pain. Quickly formatting JSON for readability is a common need. While many online formatters exist, relying on web services isn't always ideal for privacy or speed, especially with sensitive data.
This is where macOS power-user tools like Alfred and Spotlight (with a little help) come in. By building simple workflows, you can format JSON directly on your machine, right from your keyboard, without leaving your current application. This article will guide you through the process, focusing primarily on Alfred due to its robust workflow capabilities.
Why Use a Workflow?
- Speed: Format JSON with a few keystrokes.
- Convenience: Often works directly on clipboard content or selected text.
- Privacy: Your data stays on your machine.
- Customization: Tailor the formatting options to your needs.
- Offline Access: Works without an internet connection.
Workflow Basics (Alfred)
Alfred workflows chain together simple actions. For a JSON formatter, the typical flow is:
- Input: Get the JSON string (e.g., from clipboard, a typed keyword).
- Action: Process the input (run a script or command to format).
- Output: Display the formatted JSON or put it back on the clipboard.
Alfred's "Script Filter" is a powerful input type that takes a query and runs a script, expecting a specific XML or JSON output format to display results interactively. However, for a simple "format whatever is on my clipboard" action, a "Hotkey" or "Keyword" input triggering a script is more direct.
Choosing Your Formatting Tool
The core of the workflow is the command or script that does the actual formatting. Several command-line tools and built-in language modules are suitable:
- `jq`: A powerful, flexible command-line JSON processor. Excellent for formatting and querying.(Requires `jq` to be installed, e.g., via Homebrew: `brew install jq`)
echo '{}' | jq '.'
- Python: Python's `json` module can pretty-print JSON.(Python is pre-installed on macOS)
echo '{}' | python -m json.tool
- Node.js: Use `JSON.stringify` with indentation.(Requires Node.js to be installed)
echo '{}' | node -e 'process.stdin.pipe(process.stdout)'
`jq` is often the preferred tool for its speed and capabilities beyond just formatting, but Python is universally available on macOS.
Getting Input (Clipboard)
The most common way to format JSON is from the clipboard. macOS provides the `pbpaste` command to output clipboard content to standard output (stdout).
pbpaste
Putting Output (Clipboard)
Similarly, the `pbcopy` command takes standard input (stdin) and puts it onto the clipboard.
...formatted json... | pbcopy
Building the Alfred Workflow
Let's create a simple Alfred workflow that takes JSON from the clipboard, formats it using `jq`, and puts the result back on the clipboard.
Steps:
- Open Alfred Preferences > Workflows.
- Click the "+" button at the bottom left and choose "Blank Workflow".
- Give it a name (e.g., "Format JSON"), Bundle ID (reverse domain notation, e.g., `com.yourname.formatjson`), and optionally a description and icon.
- Right-click in the workflow editor and add an Input > Hotkey.
- Choose a hotkey (e.g., ⌘⇧J - Cmd+Shift+J). Leave "Argument" as "rigmarole" (doesn't matter for this simple case).
- Right-click in the workflow editor and add an Actions > Run Script.
- Link the Hotkey input to the Run Script action.
- In the Run Script action, select `/bin/bash` (or your preferred shell) and "Script".
- Enter the script. A basic one using `jq` would be:
pbpaste | jq '.' | pbcopy
This pipes the clipboard content to `jq` for formatting and then pipes the formatted output back to the clipboard.
- (Optional) Right-click and add an Output > Post Notification. Link the Run Script to this. Configure it to show a message like "JSON formatted!" to confirm success.
Now, whenever you have JSON text copied to your clipboard and press the hotkey, it will be formatted in place on the clipboard.
Using Python:
If you prefer Python, the script in the "Run Script" action would be:
pbpaste | python -m json.tool | pbcopy
Handling Invalid JSON
What happens if the clipboard contains invalid JSON? The commands (`jq`, `python -m json.tool`) will output an error message to stderr and/or exit with a non-zero status. The current simple script will likely just put the error message onto the clipboard.
To handle this more gracefully, you can add error checking in your script.
Bash script with basic error handling (using `jq`):
JSON_INPUT=$(pbpaste)
FORMATTED_JSON=$(echo "$JSON_INPUT" | jq '.' 2>&1)
if echo "$FORMATTED_JSON" | grep -q 'error:'; then
# It looks like jq returned an error
osascript -e 'display notification "Invalid JSON on clipboard." with title "JSON Formatter Error"'
else
echo "$FORMATTED_JSON" | pbcopy
osascript -e 'display notification "JSON formatted successfully." with title "JSON Formatter"'
fi
This script captures the output (including stderr from `jq` using `2>&1`), checks if it contains an error indicator (like "error:" from `jq`), and shows a notification instead of overwriting the clipboard with the error message. AppleScript (`osascript`) is used here to trigger native macOS notifications.
Spotlight Integration?
Spotlight itself is primarily a search tool and doesn't have the built-in scripting workflow capabilities of Alfred. However, you can achieve similar results through macOS Services or third-party Spotlight alternatives/extensions.
- macOS Services: You can create a Service using Automator. A Service can take selected text as input and run a script. Configure a Service to take "Text" input in "Any Application", run a "Run Shell Script" action (using `pbpaste | jq '.' | pbcopy` is tricky here as Services work on selected text, not clipboard directly unless you use `pbpaste` explicitly inside the script), and assign it a keyboard shortcut in System Preferences > Keyboard > Shortcuts > Services. This method requires selecting the JSON text first, which might be less convenient than a clipboard hotkey.
- Third-Party Apps: Some utilities or text editors might register formatters as Services or provide their own Spotlight-like interfaces.
For dedicated keyboard-driven JSON formatting workflows, Alfred offers a much more flexible and powerful platform than native Spotlight.
Beyond Basic Formatting
Once you have the basic workflow running, you can enhance it:
- Different Indentation: Use `jq -S '.'` for sorted keys, or `jq --indent 4 '.'` if your tool allows specifying indentation level. Python's `json.tool` uses 2 spaces by default.
- Minifying JSON: Change the script to `pbpaste | jq -c '.' | pbcopy` to output compact JSON on a single line.
- Opening in Editor: Instead of `pbcopy`, pipe the output to a temporary file and then use `open -a "Your Editor Name" /path/to/tempfile.json` to open the formatted JSON in your favorite text editor.
- Copying to Specific Pastboard: For advanced use, you might copy to a different pasteboard than the main clipboard.
Conclusion
Building a JSON formatter workflow in Alfred is a practical way to speed up your development tasks and keep your data private. By leveraging command-line tools like `jq` or built-in language features accessible via shell scripts, you can create powerful custom utilities triggered by simple hotkeys or keywords. While native Spotlight is less suited for this specific type of task, Alfred provides an excellent platform for automating such developer conveniences on macOS.
Need help with your JSON?
Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool