How to pretty print using jq, so that multiple values are on the same line?

爱⌒轻易说出口 提交于 2020-01-04 02:11:31

问题


What I get from jq is:

{
  "frameGrid": {
    "size": [
      24,
      24
    ],
    "dimensions": [
      1,
      1
    ],
    "names": [
      [
        "default"
      ]
    ]
  }
}

What I would like to see is something more like this:

{
  "frameGrid": {
    "size": [24,24], 
    "dimensions": [1,1],
    "names": [["default"]]
  }
}

I know both forms are valid, and that jq has a compact/pretty print mode. But is there something in-between? I'm looking to somehow format a larger json file that has many more array values than this, so that it's easily readable and printable. Maybe I'm just using the wrong tool for this job?

(please excuse the horrid formating choice. Seems code-sample doesn't like json formats much)


回答1:


While it is probably best to use a tool like the one peak suggested if your json isn't too complex you could use a second jq invocation to postprocess the output of the first. For example if your data is in data.json

$ jq -M . data.json | jq -MRsr 'gsub("\n      +";"")|gsub("\n    ]";"]")'

produces

{
  "frameGrid": {
    "size": [24,24],
    "dimensions": [1,1],
    "names": [["default"]]
  }
}



回答2:


As @jq170727 mentioned, postprocessing after a pretty-printing run of jq (e.g. jq .) is worth considering. In that vein, here is an awk script that might suffice:

#!/bin/bash

awk '
  function ltrim(x) { sub(/^[ \t]*/, "", x); return x; }
  s && NF > 1 && $NF == "["  { s=s $0;               next}
  s && NF == 1 && $1 == "]," { print s "],";   s=""; next}
  s && NF == 1 && $1 == "["  { print s;        s=$0; next}
  s && NF == 1 && $1 == "{"  { print s; print; s=""; next}
  s && NF == 1 && $1 == "]"  { print s $1;     s=""; next}
  s && NF == 1 && $1 == "}"  { print s;        s=$0; next}
  s                          { s=s ltrim($0);        next}
  $NF == "["                 { s=$0;                 next}
  {print}
'

Examples

With the example input, the invocation:

 jq . example.json | ./pp

produces:

{
  "frameGrid": {
    "size": [24,24],
    "dimensions": [1,1],
    "names": [
      ["default"]
    ]
  }
}

The invocation:

jq -n '{a:[1,2,3,[1,2,3,4]],b:2,c:{d:[1,2,{e:[3,4]}]}}' | ./pp

produces:

{
  "a": [1,2,3,
    [1,2,3,4]
  ],
  "b": 2,
  "c": {
    "d": [1,2,
      {
        "e": [3,4]
      }
    ]
  }
}


来源:https://stackoverflow.com/questions/46805833/how-to-pretty-print-using-jq-so-that-multiple-values-are-on-the-same-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!