jq icon indicating copy to clipboard operation
jq copied to clipboard

Create jqfmt to format jq scripts

Open colindean opened this issue 4 years ago • 5 comments

I've written an appreciably long jq template that I'm rationally storing in a file in invoking with jq --from-file script.jq. Frustratingly, I had to format it myself by hand in order to understand and edit it better. It'd be convenient if there was a jqfmt binary or jq fmt command built-in that could take a template and parse it, then output it in the standard formatting, kinda like gofmt, scalafmt, rustfmt, Black for Python, etc.

Example, about 13 lines from my long script bordering on "I probably should have done this in $language instead of jq":

[[ .[] | select( .algo_name | [.] | inside($algo_names | split(",")) ) ] | group_by(.strategy) | .[] | sort_by(.algo_timestamp | fromdateiso8601) | last ]

would become something like

[
    [
      .[]
      | select(
        .algo_name
        | [.]
        | inside($algo_names | split(","))
      )
    ]
    | group_by(.strategy)
    | .[]
    | sort_by(.algo_timestamp | fromdateiso8601)
    | last
  ]

with a "pretty print" option or remain like it was (manually adjusted from the latter in this example) in a "compressed" one-liner.

colindean avatar Nov 04 '21 21:11 colindean

This could also morph into a bit of a linter/best practice recommender, as reading through builtin.jq has taught me that I'm not using the built-ins very efficiently in my long template!

colindean avatar Nov 04 '21 21:11 colindean

jq program is usually very short, I mean 100 lines of jq program is like very big. Manually formatting isn't a big deal, I guess that's why nobody is working on it.

I remember there is vscode plugin that can format jq program, maybe you should try it.

xguo-prestolabs avatar Nov 16 '21 06:11 xguo-prestolabs

Hi, @colindean. I took a stab at jqfmt here: https://github.com/noperator/jqfmt. Let me know what you think!

noperator avatar Jan 08 '24 21:01 noperator

Are there even any formatting guidelines written in prose anywhere? For example, it seems everyone has different opinions on whether | should be end-of-line or start-of-next-line.

SOF3 avatar Jul 04 '24 07:07 SOF3

Not that i know of. I personally prefer and have setteled on a quite verbose "haskell"-style for bigger jq programs, see https://github.com/wader/jqjq for example how it looks.

wader avatar Jul 04 '24 08:07 wader