This repository was archived by the owner on Oct 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcompact-json-fold.py
More file actions
executable file
·71 lines (54 loc) · 2.12 KB
/
Copy pathcompact-json-fold.py
File metadata and controls
executable file
·71 lines (54 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env python3
# Author: github.com/danielhoherd and GH copilot GPT-4.1
# License: MIT
"""Fold json into a compact form while still maintaining valid syntax.
Folded lines may be longer than specified if there is no other way to maintain valid json syntax.
This is a response to https://github.com/jqlang/jq/issues/3378"""
import json
import sys
def minified_json(obj):
# Use separators to remove unnecessary whitespace
return json.dumps(obj, separators=(",", ":"))
# TODO: This algorithm is sub-optimal. There are cases where breaking before a character
# would allow the line to fall within the max length limit.
def break_json_lines(s, maxlen):
breaks = {",", "]", "}", ":"}
out = []
start = 0
in_str = False
esc = False
last_safe = None
for i, c in enumerate(s):
if in_str:
if esc:
esc = False
elif c == "\\":
esc = True
elif c == '"':
in_str = False
elif c == '"':
in_str = True
elif c in breaks:
last_safe = i + 1 # safe break after this char
# If reached maxlen, break at last safe if possible
if i - start + 1 >= maxlen and (last_safe is not None and last_safe > start):
out.append(s[start:last_safe])
start = last_safe
last_safe = None
# Append remaining
if start < len(s):
out.append(s[start:])
return "\n".join(out)
def main():
import argparse # noqa: PLC0415
parser = argparse.ArgumentParser(description="Output minified JSON with line breaks at N chars, only after allowed characters.")
parser.add_argument("input", nargs="?", type=argparse.FileType("r"), default=sys.stdin, help="Input JSON file (or stdin).")
parser.add_argument("-n", "--max-line-length", type=int, default=80, help="Maximum line length. (default: %(default)s)")
args = parser.parse_args()
# Read and load JSON
obj = json.load(args.input)
minified = minified_json(obj)
result = break_json_lines(minified, args.max_line_length)
print(result)
if __name__ == "__main__":
main()