json - 如何在 shell 脚本中缩小 JSON?

标签 json unix command-line minify

我一直在寻找一种方法来在我的 bash 控制台中丑化一些 JSON。此帮助随后在另一个命令中使用它(例如,将 json 内联传递给 httpie )

给予:

{
    "foo": "lorem",
    "bar": "ipsum"
}

我想获得:
{"foo":"lorem","bar":"ipsum"}

注意:这个问题的灵感来自 it's pretty-print counterpart .然而,谷歌搜索 bash minify json 并没有给我一个正确的结果,因此这个问题是针对 minify/uglify 的。

最佳答案

TL;DR: 使用 jj -u < my.json 似乎是最有效的,使用 jj 工具。
但是,如果您已经安装了 python 并且不想要一个新的第三方工具来完成这样的任务,python 单线是一种非常有效的方法:

python -c 'import json, sys;json.dump(json.load(sys.stdin), sys.stdout)'  < my.json
性能基准
这是脚本,使用 ruby​​ 的 benchmark-ips :
#!/usr/bin/env ruby
# frozen_string_literal: true

require "benchmark/ips"
require "tempfile"

commands= <<~SH.split("\n")
    python3 -c 'import json, sys;json.dump(json.load(sys.stdin), sys.stdout)'
    jq --compact-output
    xidel -s - -e '$json' --printed-json-format=compact
    jj -u
    yq eval -j -I=0
SH

def label(cmd)
    "%s (%s)" % [
        name = cmd.split.first,
        `#{name} --version 2>&1`[/\d+(\.\d+)*/]
    ]
end

file = Tempfile.new('foo')
file.write <<~JSON
    {
        "foo": "lorem",
        "bar": "ipsum"
    }
JSON
file.close
at_exit { file.unlink }

Benchmark.ips do |x|
    commands.each do |cmd|
        x.report(label(cmd)) do
            system(cmd, in: file.path, out: File::NULL) or raise label(cmd) + " failed"
        end
    end
    x.compare!
end
我的 mac 上的结果(16 GB 2133 MHz LPDDR3,1.4 GHz 四核 Intel Core i5):
Warming up --------------------------------------
     python3 (3.9.6)     2.000  i/100ms
            jq (1.6)     3.000  i/100ms
       xidel (0.9.8)     4.000  i/100ms
          jj (1.2.3)    19.000  i/100ms
         yq (4.11.2)    10.000  i/100ms
Calculating -------------------------------------
     python3 (3.9.6)     23.024  (± 0.0%) i/s -    116.000  in   5.040842s
            jq (1.6)     34.140  (± 2.9%) i/s -    171.000  in   5.011323s
       xidel (0.9.8)     37.127  (±13.5%) i/s -    184.000  in   5.084564s
          jj (1.2.3)    170.997  (±13.5%) i/s -    836.000  in   5.014322s
         yq (4.11.2)     83.604  (±20.3%) i/s -    400.000  in   5.041262s

Comparison:
          jj (1.2.3):      171.0 i/s
         yq (4.11.2):       83.6 i/s - 2.05x  (± 0.00) slower
       xidel (0.9.8):       37.1 i/s - 4.61x  (± 0.00) slower
            jq (1.6):       34.1 i/s - 5.01x  (± 0.00) slower
     python3 (3.9.6):       23.0 i/s - 7.43x  (± 0.00) slower
注意: Here is the pretty print benchmarkjj 也是最好的!

关于json - 如何在 shell 脚本中缩小 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61125013/

相关文章:

Java 控制台整体

python - 从 Python 完成后关闭控制台应用程序

java - 修改控制 C 命令信号以允许输入

java - 在我的数组中找到的 URL 中使用 JSON 数据

Javascript 无法正确解析 JSON 中的大量数字

java - java中如何将url中的json数据作为请求参数发送

unix - 如何在同一行中grep三个表达式

python - 让python脚本在unix的后台运行

java - 您可以使用 return 语句来简单地返回一系列字符串吗?

shell - Unix 中更改目录的别名