Bre*_*ust 7 json pretty-print jq
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 }]
},
....
]
Run Code Online (Sandbox Code Playgroud)
使用 格式化的字段--compact-output可以换行(无需打断这些长行)。
宽度受限的 JSON 漂亮打印机可以用 jq 本身编写。这是一个漂亮的打印机,它说明了如何做到这一点,尽管在目前的版本中,它的用处有限。
ppArray(indent; incr; width) 将发出 JSON 字符串流,这些字符串一起相当于tostring输入的值。为了稳健性,即使违反了宽度限制,它也始终充当漂亮的打印机。
如果输入是一个数组,并且它的元素(或递归地它们的元素)都不包含任何大对象或长字符串,则假设参数的值被合理选择并且嵌套相对于这些参数不是太深,每个发出的字符串不应长于“宽度”。
# 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
;
Run Code Online (Sandbox Code Playgroud)
[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)
Run Code Online (Sandbox Code Playgroud)
jq -nrf pp.jq
Run Code Online (Sandbox Code Playgroud)
[
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
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3295 次 |
| 最近记录: |