如何在Kate编辑器工具栏添加执行jq '.'的JSON格式化按钮
在Kate工具栏添加JSON格式化按钮(执行
jq '.') 方法1:自定义脚本+工具栏配置
- 打开Kate,点击顶部菜单栏「设置」→「配置Kate」→「脚本」→「用户脚本」
- 点击「新建脚本」,选择「Python脚本」,命名为
FormatJsonWithJq.py,粘贴以下代码:
from kate import * import subprocess def format_json_with_jq(): doc = activeDocument() if not doc: return # 获取文本:优先选中文本,无选中则取全部 selection = doc.selection() text = selection.text() if not selection.isEmpty() else doc.text() try: # 调用jq格式化 result = subprocess.run( ["jq", "."], input=text.encode("utf-8"), capture_output=True, check=True ) formatted_text = result.stdout.decode("utf-8") # 替换原内容 if selection.isEmpty(): doc.setText(formatted_text) else: doc.replaceSelection(formatted_text) except subprocess.CalledProcessError as e: message("JSON格式错误:" + e.stderr.decode("utf-8"), icon="dialog-error") except FileNotFoundError: message("未安装jq工具,请先安装", icon="dialog-error") # 注册命令到Kate registerCommand("format_json_with_jq", format_json_with_jq)
- 保存脚本后重启Kate
- 回到「配置Kate」→「工具栏」,点击「添加」,在「命令」下拉框找到
format_json_with_jq,设置按钮图标(推荐选text-x-json),命名为「JSON格式化(jq)」,确认后工具栏就会出现该按钮
方法2:扩展Filter Text插件命令
如果你习惯用Filter Text插件,可直接添加自定义命令:
- 点击「工具」→「Filter Text」→「Configure Filters」
- 点击「Add」,配置如下:
- 名称:
JSON Format (jq) - 命令:
jq '.' - 勾选「Replace selection」(按需选择替换方式)
- 名称:
- 保存后,进入「配置Kate」→「工具栏」,将这个自定义Filter命令添加到工具栏即可
注意事项
- 确保系统已安装
jq:Debian/Ubuntu用sudo apt install jq,Fedora用sudo dnf install jq,macOS用brew install jq jq对复杂JSON结构的格式化效率更高,适合处理大文件
内容的提问来源于stack exchange,提问作者alfredopacino
相关产品推荐
相关产品推荐

