You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kate编辑器工具栏添加执行jq '.'的JSON格式化按钮

在Kate工具栏添加JSON格式化按钮(执行jq '.')

方法1:自定义脚本+工具栏配置

  1. 打开Kate,点击顶部菜单栏「设置」→「配置Kate」→「脚本」→「用户脚本」
  2. 点击「新建脚本」,选择「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)
  1. 保存脚本后重启Kate
  2. 回到「配置Kate」→「工具栏」,点击「添加」,在「命令」下拉框找到format_json_with_jq,设置按钮图标(推荐选text-x-json),命名为「JSON格式化(jq)」,确认后工具栏就会出现该按钮

方法2:扩展Filter Text插件命令

如果你习惯用Filter Text插件,可直接添加自定义命令:

  1. 点击「工具」→「Filter Text」→「Configure Filters」
  2. 点击「Add」,配置如下:
    • 名称:JSON Format (jq)
    • 命令:jq '.'
    • 勾选「Replace selection」(按需选择替换方式)
  3. 保存后,进入「配置Kate」→「工具栏」,将这个自定义Filter命令添加到工具栏即可

注意事项

  • 确保系统已安装jq:Debian/Ubuntu用sudo apt install jq,Fedora用sudo dnf install jq,macOS用brew install jq
  • jq对复杂JSON结构的格式化效率更高,适合处理大文件

内容的提问来源于stack exchange,提问作者alfredopacino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 21:44:48