Skip to content

Instantly share code, notes, and snippets.

@itchyny
Created May 10, 2019 03:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itchyny/20364a7ab172e3c315b5b67c2aa1ba00 to your computer and use it in GitHub Desktop.
Save itchyny/20364a7ab172e3c315b5b67c2aa1ba00 to your computer and use it in GitHub Desktop.
JSON formatter written in jq
{ source: ., depth: 0, indent: false, first_elem: false, output: "" } |
until(
.source == "";
if .source[:1] | inside(" \t\n\r") then
.source |= .[1:]
else
.output +=
(if .first_elem and (.source[:1] | inside("]}")) then ""
else (if .first_elem then "\n" else "" end) +
(if .indent then " " * .depth
elif .source[:1] | inside("]}") then "\n" + " " * (.depth - 2)
else ""
end)
end) |
if .source[:1] | inside("[{") then
.output += .source[:1] | .source |= .[1:] | .depth += 2 | (.indent,.first_elem) = true
elif .source[:1] | inside("]}") then
.output += .source[:1] | .source |= .[1:] | .depth -= 2 | (.indent,.first_elem) = false
elif .source[:1] == "," then
.output += ",\n" | .source |= .[1:] | .indent = true
elif .source[:1] == ":" then
.output += ": " | .source |= .[1:] | .indent = false
else
(.source | match(
"^(\"(\\\\[\"\\\\/bfnrt]|\\\\u[0-9a-fA-F]{4}|[^\\\\\"])*?\"|-?(0|[1-9][0-9]*)([.][0-9]*)?([eE][-+]?[0-9]+)?|false|true|null)"
) // error) as $m | .output += $m.string | .source |= .[$m.length:] | (.indent,.first_elem) = false
end
end
) | .output
@itchyny
Copy link
Author

itchyny commented May 10, 2019

Run with cat sample.json | jq -sRrf json_format.jq.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment