如何用jq漂亮地在字符串内打印JSON?

时间:2018-11-16 22:00:28

标签: json jq pretty-print

我正在用jq编写一个更复杂的转换,而我想做的一件事就是在字符串中包含一个漂亮的JSON。例如:

echo '{"foo": "bar"}' | jq '{json: {other: .} | tostring}'

给予

{
  "json": "{\"other\":{\"foo\":\"bar\"}}"
}

我想获得:

{
  "json": "{\n  \"other\": {\n    \"foo\": \"bar\"\n  }\n}"
}

我也尝试过tojson@json,但它们给出的结果与tostring相同。可能与jq有关,还是我不得不采取其他手段?请注意,我需要在输出中包含多个带有格式化JSON的字符串,而不仅仅是示例中的一个。

2 个答案:

答案 0 :(得分:2)

此:

echo '{"foo": "bar"}' | jq '{other: .}' | jq -Rs '{json: .}'

产生:

{
  "json": "{\n  \"other\": {\n    \"foo\": \"bar\"\n  }\n}\n"
}

删除终止"\n"的一种方法是将其剥离:

echo '{"foo": "bar"}' | jq '{other: .}' | jq -Rs '{json: .[:-1]}'

答案 1 :(得分:1)

我最终编写了一个简单的格式化功能:

#   9 = \t
#  10 = \n
#  13 = \r
#  32 = (space)
#  34 = "
#  44 = ,
#  58 = :
#  91 = [
#  92 = \
#  93 = ]
# 123 = {
# 125 = }

def pretty:
  explode | reduce .[] as $char (
    {out: [], indent: [], string: false, escape: false};
    if .string == true then
      .out += [$char]
      | if $char == 34 and .escape == false then .string = false else . end
      | if $char == 92 and .escape == false then .escape = true else .escape = false end
    elif $char == 91 or $char == 123 then
      .indent += [32, 32] | .out += [$char, 10] + .indent
    elif $char == 93 or $char == 125 then
      .indent = .indent[2:] | .out += [10] + .indent + [$char]
    elif $char == 34 then
      .out += [$char] | .string = true
    elif $char == 58 then
      .out += [$char, 32]
    elif $char == 44 then
      .out += [$char, 10] + .indent
    elif $char == 9 or $char == 10 or $char == 13 or $char == 32 then
      .
    else
      .out += [$char]
    end
  ) | .out | implode;

它在空对象和数组内添加了不必要的空行,但这对我来说已经足够了。例如(单独使用):

jq -Rr 'include "pretty"; pretty' test.json

函数保存在pretty.jqtest.json文件中的位置是:

{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"key":"string with \"quotes\" and \\"},"geometry":{"type":"Polygon","coordinates":[[[24.2578125,55.178867663281984],[22.67578125,50.958426723359935],[28.125,50.62507306341435],[30.322265625000004,53.80065082633023],[24.2578125,55.178867663281984]]]}}]}

给予:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "key": "string with \"quotes\" and \\"
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              24.2578125,
              55.178867663281984
            ],
            [
              22.67578125,
              50.958426723359935
            ],
            [
              28.125,
              50.62507306341435
            ],
            [
              30.322265625000004,
              53.80065082633023
            ],
            [
              24.2578125,
              55.178867663281984
            ]
          ]
        ]
      }
    }
  ]
}