json-formatter-validator-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,229 @@
1
+ #!/usr/bin/env python3
2
+ """Format and validate JSON, with line:col errors, fail CI on bad JSON.
3
+
4
+ Run: python3 src/json_formatter_validator.py data.json
5
+ python3 src/json_formatter_validator.py --check data.json other.json
6
+ cat data.json | python3 src/json_formatter_validator.py
7
+ python3 src/json_formatter_validator.py --in-place data.json
8
+ python3 src/json_formatter_validator.py --output pretty.json data.json
9
+
10
+ The tool reads one JSON file (or standard input), pretty-formats it, and
11
+ validates it. A bad file is reported with the exact line and column of the
12
+ error, plus the offending line with a caret under the bad spot — so you can
13
+ find the mistake without opening an editor and hunting for it.
14
+
15
+ It never rewrites a file unless you ask: --in-place rewrites the input
16
+ file, --output writes the formatted text to the file you name. With no
17
+ output flag, the formatted text goes to standard output and the input file
18
+ is left alone. --check only validates and prints VALID / INVALID per file.
19
+
20
+ Exit codes: 0 when every file is valid, 1 when any file has bad JSON,
21
+ 2 for a usage or input problem (missing file, bad flag, --output with
22
+ more than one input file).
23
+
24
+ Python standard library only.
25
+ """
26
+
27
+ import argparse
28
+ import json
29
+ import sys
30
+ from pathlib import Path
31
+
32
+ VERSION = "1.0.0"
33
+
34
+
35
+ def build_parser():
36
+ """Build the command-line parser."""
37
+ parser = argparse.ArgumentParser(
38
+ prog="json_formatter_validator",
39
+ description=(
40
+ "Format and validate JSON. Prints formatted JSON to standard "
41
+ "output, or with --check prints VALID / INVALID per file. "
42
+ "Exits 1 on bad JSON, 2 on a usage problem."
43
+ ),
44
+ )
45
+ parser.add_argument(
46
+ "files",
47
+ nargs="*",
48
+ metavar="FILE",
49
+ help="JSON file to format or check. No file reads standard input.",
50
+ )
51
+ parser.add_argument(
52
+ "--check",
53
+ action="store_true",
54
+ help="Only validate: print VALID or INVALID per file, do not print JSON.",
55
+ )
56
+ parser.add_argument(
57
+ "--in-place",
58
+ action="store_true",
59
+ help="Rewrite each input file with the formatted JSON.",
60
+ )
61
+ parser.add_argument(
62
+ "--output",
63
+ metavar="FILE",
64
+ help="Write the formatted JSON to this file instead of standard output.",
65
+ )
66
+ parser.add_argument(
67
+ "--indent",
68
+ type=int,
69
+ default=2,
70
+ metavar="N",
71
+ help="Spaces per indent level (0-8, default 2). Ignored with --minify.",
72
+ )
73
+ parser.add_argument(
74
+ "--sort-keys",
75
+ action="store_true",
76
+ help="Sort object keys alphabetically in the output.",
77
+ )
78
+ parser.add_argument(
79
+ "--minify",
80
+ action="store_true",
81
+ help="Write compact JSON with no extra spaces or newlines.",
82
+ )
83
+ parser.add_argument(
84
+ "--version",
85
+ action="version",
86
+ version="%(prog)s " + VERSION,
87
+ )
88
+ return parser
89
+
90
+
91
+ def format_text(text, indent=2, sort_keys=False, minify=False):
92
+ """Parse JSON text and return (value, formatted_text).
93
+
94
+ Raises json.JSONDecodeError on bad JSON, exactly as the stdlib
95
+ reports it (with lineno and colno).
96
+ """
97
+ value = json.loads(text)
98
+ if minify:
99
+ formatted = json.dumps(
100
+ value, sort_keys=sort_keys, separators=(",", ":"), ensure_ascii=True
101
+ )
102
+ else:
103
+ formatted = json.dumps(
104
+ value, indent=indent, sort_keys=sort_keys, ensure_ascii=True
105
+ )
106
+ return value, formatted
107
+
108
+
109
+ def describe_error(source, text, error):
110
+ """Build the error report lines for a JSONDecodeError.
111
+
112
+ Returns a list of lines: the one-line report with line:col, then the
113
+ offending source line and a caret under the bad column, when the
114
+ source line exists.
115
+ """
116
+ lines = [
117
+ "INVALID %s:%d:%d: %s" % (source, error.lineno, error.colno, error.msg)
118
+ ]
119
+ source_lines = text.splitlines()
120
+ if 1 <= error.lineno <= len(source_lines):
121
+ lines.append(" " + source_lines[error.lineno - 1])
122
+ lines.append(" " + " " * (error.colno - 1) + "^")
123
+ return lines
124
+
125
+
126
+ def read_input(path):
127
+ """Read a file as UTF-8 text. Raises OSError / UnicodeDecodeError."""
128
+ return Path(path).read_text(encoding="utf-8")
129
+
130
+
131
+ def process_one(source, text, indent, sort_keys, minify, check, out_lines):
132
+ """Format or check one input. Returns True when the JSON is valid.
133
+
134
+ Appends report lines to out_lines. In format mode the formatted JSON
135
+ itself is returned as the second value; in check mode it is None.
136
+ """
137
+ try:
138
+ _value, formatted = format_text(text, indent, sort_keys, minify)
139
+ except json.JSONDecodeError as error:
140
+ out_lines.extend(describe_error(source, text, error))
141
+ return False, None
142
+ if check:
143
+ out_lines.append("VALID %s" % source)
144
+ return True, None
145
+ return True, formatted
146
+
147
+
148
+ def run(argv=None, stdin_text=None, stdout=None, stderr=None):
149
+ """Run the CLI. Returns the exit code. Testable without subprocess."""
150
+ stdout = sys.stdout if stdout is None else stdout
151
+ stderr = sys.stderr if stderr is None else stderr
152
+ parser = build_parser()
153
+ args = parser.parse_args(argv)
154
+
155
+ if args.indent < 0 or args.indent > 8:
156
+ print("error: --indent must be 0-8", file=stderr)
157
+ return 2
158
+ if args.output and args.check:
159
+ print("error: --output cannot be used with --check", file=stderr)
160
+ return 2
161
+ if args.output and args.in_place:
162
+ print("error: --output cannot be used with --in-place", file=stderr)
163
+ return 2
164
+ if args.in_place and args.check:
165
+ print("error: --in-place cannot be used with --check", file=stderr)
166
+ return 2
167
+ if args.in_place and not args.files:
168
+ print("error: --in-place needs a file, it cannot rewrite stdin", file=stderr)
169
+ return 2
170
+ if args.output and len(args.files) != 1:
171
+ print("error: --output needs exactly one input file", file=stderr)
172
+ return 2
173
+ if not args.check and len(args.files) > 1 and not args.in_place:
174
+ print(
175
+ "error: formatting more than one file needs --check or --in-place",
176
+ file=stderr,
177
+ )
178
+ return 2
179
+
180
+ inputs = [] # list of (source_name, text)
181
+ if not args.files:
182
+ if stdin_text is None:
183
+ stdin_text = sys.stdin.read()
184
+ inputs.append(("<stdin>", stdin_text))
185
+ else:
186
+ for path in args.files:
187
+ try:
188
+ inputs.append((path, read_input(path)))
189
+ except FileNotFoundError:
190
+ print("error: file not found: %s" % path, file=stderr)
191
+ return 2
192
+ except OSError as exc:
193
+ print("error: cannot read %s: %s" % (path, exc), file=stderr)
194
+ return 2
195
+ except UnicodeDecodeError:
196
+ print("error: %s is not valid UTF-8 text" % path, file=stderr)
197
+ return 2
198
+
199
+ all_valid = True
200
+ for source, text in inputs:
201
+ out_lines = []
202
+ valid, formatted = process_one(
203
+ source, text, args.indent, args.sort_keys, args.minify, args.check, out_lines
204
+ )
205
+ if not valid:
206
+ all_valid = False
207
+ for line in out_lines:
208
+ print(line, file=stdout)
209
+ continue
210
+ if args.check:
211
+ print(out_lines[0], file=stdout)
212
+ elif args.in_place:
213
+ Path(source).write_text(formatted + "\n", encoding="utf-8")
214
+ print("formatted %s" % source, file=stdout)
215
+ elif args.output:
216
+ Path(args.output).write_text(formatted + "\n", encoding="utf-8")
217
+ print("formatted %s -> %s" % (source, args.output), file=stdout)
218
+ else:
219
+ print(formatted, file=stdout)
220
+
221
+ return 0 if all_valid else 1
222
+
223
+
224
+ def main():
225
+ sys.exit(run())
226
+
227
+
228
+ if __name__ == "__main__":
229
+ main()
@@ -0,0 +1,288 @@
1
+ Metadata-Version: 2.4
2
+ Name: json-formatter-validator-cli
3
+ Version: 0.1.0
4
+ Summary: Format and validate JSON, with line:col errors, fail CI on bad JSON.
5
+ Author: Haider Ali
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/haiderstudio/json-formatter-validator-cli
8
+ Project-URL: Repository, https://github.com/haiderstudio/json-formatter-validator-cli
9
+ Project-URL: Issues, https://github.com/haiderstudio/json-formatter-validator-cli/issues
10
+ Keywords: json,formatter,validator,cli,developer-tools
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Software Development
17
+ Requires-Python: >=3.9
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Dynamic: license-file
21
+
22
+ # json-formatter-validator-cli
23
+
24
+ Format and validate JSON, with line:col errors, fail CI on bad JSON.
25
+
26
+ [![CI](https://github.com/haiderstudio/json-formatter-validator-cli/actions/workflows/ci.yml/badge.svg)](https://github.com/haiderstudio/json-formatter-validator-cli/actions/workflows/ci.yml) [![Licence: MIT](https://img.shields.io/badge/Licence-MIT-yellow.svg)](LICENSE)
27
+
28
+ ## What it does
29
+
30
+ `json_formatter_validator` reads a JSON file (or standard input),
31
+ pretty-formats it, and validates it. A bad file is reported with the
32
+ exact line and column of the error, plus the offending line with a
33
+ caret under the bad spot — so you can find the mistake without
34
+ opening an editor and hunting for it.
35
+
36
+ - It formats one file to standard output by default (2-space indent).
37
+ `--indent N` changes the indent, `--sort-keys` sorts object keys,
38
+ `--minify` writes compact JSON with no extra spaces or newlines.
39
+ - It reads from standard input when no file is named, so it works in
40
+ a pipe.
41
+ - `--check` only validates: it prints `VALID` or `INVALID` per file
42
+ and checks as many files as you name. It exits 1 when any file has
43
+ bad JSON, so it can fail a CI run.
44
+ - It never rewrites a file unless you ask: `--in-place` rewrites the
45
+ input file, `--output FILE` writes the formatted text to the file
46
+ you name. A bad file is never rewritten — it is reported and left
47
+ alone.
48
+ - It is report-only and runs fully offline: it sends nothing anywhere
49
+ and needs no API key.
50
+
51
+ ## What it does NOT do
52
+
53
+ - It does not check JSON against a schema. It checks syntax only: can
54
+ a parser read this text, and where exactly does it break.
55
+ - It does not fix bad JSON. A missing comma is reported with its line
56
+ and column, not repaired.
57
+ - It does not check duplicate keys, and it does not warn about them.
58
+ Two keys with the same name are read the way Python's `json` module
59
+ reads them (the last one wins).
60
+ - It does not query, filter, or transform JSON. If you need to pick
61
+ fields out of a document, that is a different tool's job.
62
+ - It does not accept comments, trailing commas, or single quotes.
63
+ Those are not JSON, and they are reported as errors.
64
+
65
+ ## Who it is for
66
+
67
+ Anyone who keeps JSON files around and wants a quick, scriptable
68
+ check that they are well-formed: a developer adding a CI step that
69
+ fails the build on a broken config, someone hand-editing a settings
70
+ file, or anyone piping API output through a formatter to read it. If
71
+ the file is valid, you get clean formatted JSON; if it is not, the
72
+ report says exactly which line and column broke.
73
+
74
+ ## How this differs from similar tools
75
+
76
+ JSON formatters already exist, and most of them are web pages or
77
+ editors: JSONLint and jsonformatter.org format in a browser, and the
78
+ top GitHub hit for the exact name, mariazevedo88/json-formatter-validator
79
+ (12 stars), is a Java tool. The big command-line name in this space
80
+ is jq, but jq is a query and transform language — formatting is a
81
+ side effect of it, not its job, and it needs a separate install.
82
+ Python already ships `python -m json.tool`, which pretty-prints and
83
+ exits nonzero on bad JSON, but it reports only the error message: no
84
+ line and column pointer, no `--check` mode for several files at once,
85
+ and no `--in-place` or `--output` for writing formatted files.
86
+ Schema validators such as the ajv CLI or jsonvalidator-cli check JSON
87
+ against a schema, which is a different job from checking syntax.
88
+
89
+ This tool does a narrower job: a Python standard-library-only CLI
90
+ that formats one file or checks many, reports every error with a
91
+ line, a column, and a caret, and exits 1 on bad JSON for CI — no
92
+ install beyond Python, no browser, no schema, no query language.
93
+
94
+ ## Install
95
+
96
+ Python standard library only — no packages to download. Clone the
97
+ repo and run it in place:
98
+
99
+ ```sh
100
+ git clone https://github.com/haiderstudio/json-formatter-validator-cli.git
101
+ cd json-formatter-validator-cli
102
+ ```
103
+
104
+ Python 3.10 or newer.
105
+
106
+ ## Usage
107
+
108
+ Format a file:
109
+
110
+ ```sh
111
+ python3 src/json_formatter_validator.py examples/compact.json
112
+ ```
113
+
114
+ Real output:
115
+
116
+ ```text
117
+ {
118
+ "name": "example-site",
119
+ "pages": [
120
+ {
121
+ "draft": false,
122
+ "path": "/",
123
+ "title": "Home"
124
+ },
125
+ {
126
+ "draft": false,
127
+ "path": "/about",
128
+ "title": "About"
129
+ }
130
+ ],
131
+ "private": false,
132
+ "settings": {
133
+ "postsPerPage": 10,
134
+ "theme": "light"
135
+ },
136
+ "version": "1.4.0"
137
+ }
138
+ ```
139
+
140
+ The command exits 0. The input file is left alone.
141
+
142
+ Check several files at once:
143
+
144
+ ```sh
145
+ python3 src/json_formatter_validator.py --check examples/valid.json examples/compact.json examples/invalid-missing-comma.json examples/invalid-trailing-comma.json examples/invalid-single-quotes.json
146
+ ```
147
+
148
+ Real output:
149
+
150
+ ```text
151
+ VALID examples/valid.json
152
+ VALID examples/compact.json
153
+ INVALID examples/invalid-missing-comma.json:4:3: Expecting ',' delimiter
154
+ "private": false
155
+ ^
156
+ INVALID examples/invalid-trailing-comma.json:4:1: Expecting property name enclosed in double quotes
157
+ }
158
+ ^
159
+ INVALID examples/invalid-single-quotes.json:2:3: Expecting property name enclosed in double quotes
160
+ 'name': 'example-site',
161
+ ^
162
+ ```
163
+
164
+ The command exits 1, because three files are bad. The same output
165
+ is saved in `examples/sample-output.txt`.
166
+
167
+ Format from a pipe, with sorted keys:
168
+
169
+ ```sh
170
+ echo '{"b":1,"a":2}' | python3 src/json_formatter_validator.py --sort-keys
171
+ ```
172
+
173
+ Real output:
174
+
175
+ ```text
176
+ {
177
+ "a": 2,
178
+ "b": 1
179
+ }
180
+ ```
181
+
182
+ Minify a file:
183
+
184
+ ```sh
185
+ python3 src/json_formatter_validator.py --minify examples/valid.json
186
+ ```
187
+
188
+ Real output:
189
+
190
+ ```text
191
+ {"name":"example-site","pages":[{"draft":false,"path":"/","title":"Home"},{"draft":false,"path":"/about","title":"About"}],"private":false,"settings":{"postsPerPage":10,"theme":"light"},"version":"1.4.0"}
192
+ ```
193
+
194
+ ## Examples
195
+
196
+ ### 1. Fail CI on a bad config file
197
+
198
+ ```sh
199
+ python3 src/json_formatter_validator.py --check config.json
200
+ echo $?
201
+ ```
202
+
203
+ ```text
204
+ 1
205
+ ```
206
+
207
+ The exit code is 1 when the file has bad JSON. Put the same command
208
+ in CI and the build fails until the file is fixed. With a valid file
209
+ the same command prints `VALID config.json` and exits 0.
210
+
211
+ ### 2. A missing comma, found by line and column
212
+
213
+ `examples/invalid-missing-comma.json` is missing the comma after
214
+ `"version": "1.4.0"`:
215
+
216
+ ```sh
217
+ python3 src/json_formatter_validator.py --check examples/invalid-missing-comma.json
218
+ ```
219
+
220
+ ```text
221
+ INVALID examples/invalid-missing-comma.json:4:3: Expecting ',' delimiter
222
+ "private": false
223
+ ^
224
+ ```
225
+
226
+ Line 4, column 3 — the start of `"private"` — is where the parser
227
+ expected the comma. The caret points at it.
228
+
229
+ ### 3. Rewrite a file in place, only when asked
230
+
231
+ ```sh
232
+ python3 src/json_formatter_validator.py --in-place examples/compact.json
233
+ ```
234
+
235
+ ```text
236
+ formatted examples/compact.json
237
+ ```
238
+
239
+ The file is now pretty-printed. Without `--in-place` (or
240
+ `--output`), the same command prints the formatted text and leaves
241
+ the file alone. A bad file is never rewritten, even with
242
+ `--in-place`.
243
+
244
+ ## How it is tested
245
+
246
+ ```sh
247
+ python3 tests/test_json_formatter_validator.py
248
+ ```
249
+
250
+ 35 tests, standard library `unittest` only — no third-party
251
+ packages. They cover: formatting (default indent, `--indent 4`,
252
+ indent 0, `--sort-keys`, `--minify`, non-ASCII escaping), error
253
+ positions (missing comma at 4:3, trailing data at 1:9, empty input
254
+ at 1:1, trailing comma, single quotes), the `--check` mode (valid
255
+ and invalid mixed, all valid, stdin, pointer lines), the write modes
256
+ (`--in-place` rewrites and reports, bad files are never rewritten,
257
+ `--output` writes a named file, plain formatting never changes the
258
+ input), the usage errors (missing file, bad indent, `--output` with
259
+ two files, `--in-place` with stdin), the bundled examples (the
260
+ committed `examples/sample-output.txt` is compared against a fresh
261
+ run, and the README's quoted outputs are checked against it), the
262
+ example script, and a check that the code and the tests import
263
+ standard library only.
264
+
265
+ The bundled example is a real run, not made-up output:
266
+
267
+ ```sh
268
+ sh examples/run-example.sh
269
+ ```
270
+
271
+ It formats `examples/compact.json`, checks all five example files,
272
+ and formats one line from stdin. The committed
273
+ `examples/sample-output.txt` is the output of the check run.
274
+
275
+ ## Contributing
276
+
277
+ Small, focused improvements are welcome — see
278
+ [CONTRIBUTING.md](CONTRIBUTING.md).
279
+
280
+ ## Licence
281
+
282
+ MIT — see [LICENSE](LICENSE).
283
+
284
+ ## Original work
285
+
286
+ Built from scratch for this repo. The JSON parsing and error
287
+ positions come from Python's standard `json` module; no code was
288
+ copied from any existing formatter or validator.
@@ -0,0 +1,7 @@
1
+ json_formatter_validator.py,sha256=063iIbtcCOvmFMiu2VyrZfISXMzsuW5ceXv8wK4rep8,7841
2
+ json_formatter_validator_cli-0.1.0.dist-info/licenses/LICENSE,sha256=mTjYlQM7htiV7thgBkBwT0woURqRpTJG1eWK1Logfl8,1067
3
+ json_formatter_validator_cli-0.1.0.dist-info/METADATA,sha256=arETv9P-v3YnS3iH-3C1iLe3APvtUMKf8HPlQvqZCXk,9290
4
+ json_formatter_validator_cli-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ json_formatter_validator_cli-0.1.0.dist-info/entry_points.txt,sha256=W81e-ArVtyZedhAi36IqjkA7ymz-wP4CUPgxUN2BLqo,75
6
+ json_formatter_validator_cli-0.1.0.dist-info/top_level.txt,sha256=cvYwNfxRRKWyhBYz-MVwsE-M0OV2mI3vOSiX8BWlLg8,25
7
+ json_formatter_validator_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ json-formatter-validator = json_formatter_validator:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Haider Ali
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ json_formatter_validator