一篇在 Hacker News 上分享的文章介绍了利用 jq 工具快速格式化剪贴板中 JSON 数据的实用方法1。作者通过 shell 别名简化操作流程,使用户能够一键将剪贴板内的 JSON 自动整理并返回剪贴板1。
针对不同操作系统,该方案提供了差异化的命令实现1。在 macOS 上,用户可以设置别名 alias jsontidy="pbpaste | jq '.' | pbcopy" 来完成格式化操作1。Linux 用户则可采用 xclip -selection clipboard -o | jq '.' | xclip -selection clipboard 的命令组合实现相同功能1。为了增强健壮性,作者还提供了一个改进的错误处理版本:alias jsontidy="xclip -selection clipboard -o | (jq '.' || xclip -selection clipboard -o) | xclip -selection clipboard"1,确保当 JSON 格式不正确时,原始内容能够得以保留1。
A technique for efficiently formatting JSON data directly from the clipboard has been shared, leveraging the jq command-line tool to streamline common development workflows. 1 The approach involves creating shell aliases that automatically process clipboard contents, making it practical for developers who frequently work with JSON data. 1
On macOS, the solution uses a simple alias that reads clipboard data via pbpaste, pipes it through jq for formatting, and returns the result to the clipboard with pbcopy: alias jsontidy="pbpaste | jq '.' | pbcopy". 1 For Linux users, an equivalent command substitutes clipboard utilities, using xclip -selection clipboard -o | jq '.' | xclip -selection clipboard to achieve the same result. 1
An enhanced version incorporating error handling has also been proposed for Linux systems: alias jsontidy="xclip -selection clipboard -o | (jq '.' || xclip -selection clipboard -o) | xclip -selection clipboard". 1 This variant preserves the original clipboard content if jq encounters invalid JSON, preventing data loss when malformed input is encountered. 1
评论
还没有评论,欢迎留下第一条。