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

如何使用Unix命令或Shell脚本无需安装额外工具实现JSON格式化

无额外依赖的JSON格式化实现方案

以下两种方案均使用Unix系统默认自带工具,无需安装jq、json_reformat等任何第三方软件。

方案1:Python单行命令(优先推荐)

绝大多数Unix、Linux、macOS系统默认预装Python,自带的json.tool模块可直接完成JSON格式化,支持任意复杂嵌套结构,兼容性最好:

  • 格式化本地JSON文件:python -m json.tool 目标文件路径
  • 处理管道输入的JSON内容:
    echo '{ "name": "Ram", "age": "56" }' | python -m json.tool
    
    若系统默认Python版本为3,可将命令中的python替换为python3,效果一致。

方案2:纯awk实现(适配无Python的极端环境)

如果系统没有Python,可使用默认自带的awk工具实现简单JSON格式化,脚本如下:

awk '
BEGIN {
    indent = 0
    in_string = 0
}
{
    line = $0
    len = length(line)
    for (i = 1; i <= len; i++) {
        c = substr(line, i, 1)
        if (c == "\"" && substr(line, i-1, 1) != "\\") {
            in_string = !in_string
        }
        if (!in_string) {
            if (c == "{" || c == "[") {
                print ""
                for (j = 0; j < indent; j++) printf "    "
                printf "%c", c
                indent++
                print ""
                for (j = 0; j < indent; j++) printf "    "
            } else if (c == "}" || c == "]") {
                indent--
                print ""
                for (j = 0; j < indent; j++) printf "    "
                printf "%c", c
            } else if (c == ",") {
                printf "%c", c
                print ""
                for (j = 0; j < indent; j++) printf "    "
            } else if (c != " " && c != "\t" && c != "\n") {
                printf "%c", c
            }
        } else {
            printf "%c", c
        }
    }
}
END {
    print ""
}
'

使用方法示例:

echo '{ "name": "Ram", "age": "56" }' | 上述awk脚本内容

输出效果

两种方案针对示例输入的输出结果均符合要求:

{
    "name": "Ram",
    "age": "56"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 11:15:07