gpt4 book ai didi

json - 使用 jq 将某些字段格式化为紧凑格式?

转载 作者:行者123 更新时间:2023-12-04 17:53:09 26 4
gpt4 key购买 nike

jq 是 pretty-print 任意 JSON 的最佳选择吗?
cat my.json | jq .漂亮地打印给定的 JSON,但在单独的行上扩展每个字段。

但是如果某些字段是重复的,例如点列表怎么办?如何使用 --compact-output 将匹配模式的字段格式化为一行?

例如,将下面的“coords”和“list”字段格式化为一行:

 [
{
"field1": {
"a": "",
"b": ""
"list": [{ "name": "x", "score": 1, "rect": { "x": 156, "y": 245, "w": 35, "h": 45 }, ... ]
},
"field2": 2,
"coords": [{ "x": 100, "y": 400 },{ "x": 100, "y": 0 }]
},
....
]

--compact-output 格式化的字段可以包装(不需要打破这些长线)。

最佳答案

可以用 jq 本身编写一个宽度受限的 JSON pretty-print 。
这是一个 pretty-print ,它说明了如何做到这一点,尽管在目前的化身中,它的用处有限。

ppArray(indent; incr; width) 将发出一个 JSON 字符串流
加起来相当于tostring输入的值。为了
健壮性,它将始终充当 pretty-print ,即使
违反了宽度限制。

如果输入是一个数组,并且如果没有它的元素(或递归
它们的元素)包含任何大对象或长字符串,然后假设参数的值被合理选择并且嵌套相对于这些参数不是太深,
每个发出的字符串不应超过“宽度”。

# indent is the initial indentation level;
# incr is the number of spaces to add for one additional indentation level;
# width is the target maximum width.
#
def ppArray(indent; incr; width):
# The inner function produces an array of unindented strings.
def ppArray_(incr_; width_):
tostring as $tostring
| if $tostring|length <= (width_ - incr_) then [$tostring]
else reduce .[] as $i
([];
($i|tostring) as $is
| if length == 0 then [ $is ]
else .[-1] as $s
| ($s|length) as $n
| ($is|length) as $isl
| if $n + $isl <= (width_ - incr_)
then .[-1] = ($s + ", " + $is)
elif ($i|type) == "array"
then (.[-1]+=",") + [ $i | ppArray(0; incr_; width_ - incr_) ]
else (.[-1]+=",") + [ $is ]
end
end )
end;

(" " * indent) as $indentation
| if type == "array"
then ppArray_(incr; width - indent)
| $indentation + "[",
(.[] | ($indentation + " " + . )),
$indentation + "]"
else $indentation + tostring
end
;

例子:
[range(0;16)]
|
(ppArray(0; 2; 10)),
"::",
([{a:1}, {b:2}, {c:3}] | ppArray(0; 2; 10)),
"::",
(.[2]=[range(0;10)]) | ppArray(0; 2; 10)

调用:
jq -nrf pp.jq

输出:
[
0, 1, 2, 3,
4, 5, 6, 7,
8, 9, 10,
11, 12, 13,
14, 15
]
::
[
{"a":1},
{"b":2},
{"c":3}
]
::
[
0, 1,
[
0, 1, 2,
3, 4, 5,
6, 7, 8,
9
], 3, 4, 5,
6, 7, 8, 9,
10, 11, 12,
13, 14, 15
]

关于json - 使用 jq 将某些字段格式化为紧凑格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42729731/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com