如何使用 jq 为每个根级对象键打印一行?

问题描述 投票:0回答:1

我想通过以紧凑模式打印来压缩 json 文件的空间 (

-c
),但我想在每个根级对象后面添加一个新行。

例如,对于以下对象

{
  "a": {
    "a1": 1,
    "a2": [
      null
    ]
  },
  "b": {
    "b1": "test"
  },
  "c": [
    1,
    2,
    3
  ]
}

我想将其打印为

{
"a":{"a1":1,"a2":[null]},
"b":{"b1":"test"},
"c":[1,2,3]
}

即每行一个根级对象(添加开始/结束括号)

我使用

将每一项打印在一行中
echo '{"a":{"a1":1, "a2":[null]}, "b": {"b1":"test"}, "c": [1,2,3]}' | jq -c -r '. | to_entries | .[] | "\"\(.key)\": \(.value)"'

"a": {"a1":1,"a2":[null]}
"b": {"b1":"test"}
"c": [1,2,3]

但我无法形成单个有效的 JSON 对象。

有人可以提供一些建议吗? 谢谢

json shell command-line jq text-processing
1个回答
0
投票

jq 如何进行漂亮打印的选择非常有限。 最好的选择是自己编写。这是使用

to_entries
@json

的非常手动的方法
jq -r '
  "{", (to_entries
    | (.[:-1][] | @json "\(.key):\(.value),"),
      (last | @json "\(.key):\(.value)")
  ), "}"
'
{
"a":{"a1":1,"a2":[null]},
"b":{"b1":"test"},
"c":[1,2,3]
}

演示

© www.soinside.com 2019 - 2024. All rights reserved.