使用jq将某些字段格式化为Compact?

时间:2017-03-11 00:04:28

标签: json pretty-print jq

jq是漂亮打印任意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格式化的字段可以换行(不需要打破这些长行)。

1 个答案:

答案 0 :(得分:0)

约束宽度的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
;

实施例

[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
]