Created
May 10, 2019 03:32
-
-
Save itchyny/20364a7ab172e3c315b5b67c2aa1ba00 to your computer and use it in GitHub Desktop.
JSON formatter written in jq
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run with
cat sample.json | jq -sRrf json_format.jq
.