0
# Command Line Interface
1
2
Command-line tools for JSON Schema validation from the command line with various output formats and options. The CLI provides convenient access to validation functionality for scripts, automation, and interactive use.
3
4
## Capabilities
5
6
### Main CLI Class
7
8
Entry point for command-line JSON Schema validation.
9
10
```java { .api }
11
/**
12
* Main class for command-line JSON Schema validation
13
*/
14
public final class Main {
15
/**
16
* Command-line entry point for JSON Schema validation
17
* @param args Command-line arguments
18
*/
19
public static void main(String... args);
20
}
21
```
22
23
### Return Codes
24
25
Standardized exit codes for CLI operations.
26
27
```java { .api }
28
/**
29
* Exit codes for command-line validation operations
30
*/
31
enum RetCode {
32
/**
33
* Validation completed successfully (exit code 0)
34
*/
35
ALL_OK(0),
36
37
/**
38
* Command-line usage error (exit code 2)
39
*/
40
CMD_ERROR(2),
41
42
/**
43
* Instance validation failed (exit code 100)
44
*/
45
VALIDATION_FAILURE(100),
46
47
/**
48
* Schema syntax error detected (exit code 101)
49
*/
50
SCHEMA_SYNTAX_ERROR(101);
51
52
/**
53
* Get numeric exit code
54
* @return int exit code value
55
*/
56
int get();
57
}
58
```
59
60
### Reporter Interface
61
62
Interface for formatting and outputting validation results.
63
64
```java { .api }
65
/**
66
* Interface for reporting validation results in different formats
67
*/
68
public interface Reporter {
69
/**
70
* Report validation results
71
* @param report ProcessingReport containing validation results
72
* @throws IOException if output writing fails
73
*/
74
void reportValidation(ProcessingReport report) throws IOException;
75
}
76
```
77
78
### Reporters Factory
79
80
Factory for creating different types of result reporters.
81
82
```java { .api }
83
/**
84
* Factory for creating validation result reporters
85
*/
86
public final class Reporters {
87
/**
88
* Create default console reporter
89
* @return Reporter that outputs to standard output
90
*/
91
public static Reporter getDefault();
92
93
/**
94
* Create JSON format reporter
95
* @return Reporter that outputs JSON formatted results
96
*/
97
public static Reporter getJSON();
98
99
/**
100
* Create brief format reporter
101
* @return Reporter that outputs minimal validation results
102
*/
103
public static Reporter getBrief();
104
}
105
```
106
107
## Command Line Usage
108
109
### Basic Validation
110
111
```bash
112
# Validate instance against schema
113
java -jar json-schema-validator.jar schema.json instance.json
114
115
# Using Maven exec plugin
116
mvn exec:java -Dexec.mainClass="com.github.fge.jsonschema.main.cli.Main" \
117
-Dexec.args="schema.json instance.json"
118
119
# Using Gradle
120
gradle run --args="schema.json instance.json"
121
```
122
123
### Command Line Options
124
125
```bash
126
# Basic validation (schema and instance)
127
java -jar json-schema-validator.jar schema.json instance.json
128
129
# Brief output (only show validation status OK/NOT OK)
130
java -jar json-schema-validator.jar --brief schema.json instance.json
131
java -jar json-schema-validator.jar -s schema.json instance.json
132
133
# Quiet mode (no output, only exit codes)
134
java -jar json-schema-validator.jar --quiet schema.json instance.json
135
java -jar json-schema-validator.jar -q schema.json instance.json
136
137
# Validate multiple instances against same schema
138
java -jar json-schema-validator.jar schema.json instance1.json instance2.json
139
140
# Syntax validation only (validate schema syntax)
141
java -jar json-schema-validator.jar --syntax schema.json
142
143
# Set fake root for URI resolution
144
java -jar json-schema-validator.jar --fakeroot http://example.com/ schema.json instance.json
145
146
# Help information
147
java -jar json-schema-validator.jar --help
148
```
149
150
### Exit Codes
151
152
- **0 (ALL_OK)**: Validation successful, all instances are valid
153
- **2 (CMD_ERROR)**: Invalid command-line usage
154
- **100 (VALIDATION_FAILURE)**: One or more instances failed validation
155
- **101 (SCHEMA_SYNTAX_ERROR)**: Schema has syntax errors
156
157
## Usage Examples
158
159
### Example 1: Basic CLI Validation Script
160
161
```bash
162
#!/bin/bash
163
# validate-json.sh - JSON validation script
164
165
SCHEMA_FILE="$1"
166
INSTANCE_FILE="$2"
167
168
if [ $# -ne 2 ]; then
169
echo "Usage: $0 <schema-file> <instance-file>"
170
exit 1
171
fi
172
173
if [ ! -f "$SCHEMA_FILE" ]; then
174
echo "Error: Schema file '$SCHEMA_FILE' not found"
175
exit 1
176
fi
177
178
if [ ! -f "$INSTANCE_FILE" ]; then
179
echo "Error: Instance file '$INSTANCE_FILE' not found"
180
exit 1
181
fi
182
183
echo "Validating $INSTANCE_FILE against $SCHEMA_FILE..."
184
185
java -jar json-schema-validator-2.2.6-lib.jar "$SCHEMA_FILE" "$INSTANCE_FILE"
186
exit_code=$?
187
188
case $exit_code in
189
0)
190
echo "✓ Validation successful"
191
;;
192
2)
193
echo "✗ Command line error"
194
;;
195
100)
196
echo "✗ Validation failed"
197
;;
198
101)
199
echo "✗ Schema syntax error"
200
;;
201
*)
202
echo "✗ Unknown error (exit code: $exit_code)"
203
;;
204
esac
205
206
exit $exit_code
207
```
208
209
### Example 2: Batch Validation Script
210
211
```bash
212
#!/bin/bash
213
# batch-validate.sh - Validate multiple files against a schema
214
215
SCHEMA_FILE="$1"
216
shift
217
INSTANCE_FILES=("$@")
218
219
if [ -z "$SCHEMA_FILE" ] || [ ${#INSTANCE_FILES[@]} -eq 0 ]; then
220
echo "Usage: $0 <schema-file> <instance-file1> [instance-file2] ..."
221
exit 1
222
fi
223
224
echo "Schema: $SCHEMA_FILE"
225
echo "Validating ${#INSTANCE_FILES[@]} instance(s)..."
226
echo
227
228
overall_success=true
229
230
for instance in "${INSTANCE_FILES[@]}"; do
231
echo -n "Validating $instance... "
232
233
java -jar json-schema-validator-2.2.6-lib.jar "$SCHEMA_FILE" "$instance" --brief > /dev/null 2>&1
234
exit_code=$?
235
236
case $exit_code in
237
0)
238
echo "✓ VALID"
239
;;
240
2)
241
echo "✗ CMD ERROR"
242
overall_success=false
243
;;
244
100)
245
echo "✗ INVALID"
246
overall_success=false
247
;;
248
101)
249
echo "✗ SCHEMA ERROR"
250
overall_success=false
251
;;
252
*)
253
echo "✗ ERROR ($exit_code)"
254
overall_success=false
255
;;
256
esac
257
done
258
259
echo
260
if $overall_success; then
261
echo "All validations passed"
262
exit 0
263
else
264
echo "Some validations failed"
265
exit 1
266
fi
267
```
268
269
### Example 3: Integration with CI/CD Pipeline
270
271
```yaml
272
# .github/workflows/validate-schemas.yml
273
name: Validate JSON Schemas
274
275
on: [push, pull_request]
276
277
jobs:
278
validate:
279
runs-on: ubuntu-latest
280
281
steps:
282
- uses: actions/checkout@v2
283
284
- name: Set up Java
285
uses: actions/setup-java@v2
286
with:
287
java-version: '8'
288
distribution: 'adopt'
289
290
- name: Download JSON Schema Validator
291
run: |
292
wget https://github.com/fge/json-schema-validator/releases/download/2.2.6/json-schema-validator-2.2.6-lib.jar
293
294
- name: Validate API Schemas
295
run: |
296
for schema in schemas/*.json; do
297
echo "Validating schema: $schema"
298
java -jar json-schema-validator-2.2.6-lib.jar --syntax-only "$schema"
299
if [ $? -ne 0 ]; then
300
echo "Schema validation failed for $schema"
301
exit 1
302
fi
303
done
304
305
- name: Validate Test Data
306
run: |
307
for data in test-data/*.json; do
308
echo "Validating data: $data against schemas/api-schema.json"
309
java -jar json-schema-validator-2.2.6-lib.jar schemas/api-schema.json "$data"
310
if [ $? -ne 0 ]; then
311
echo "Data validation failed for $data"
312
exit 1
313
fi
314
done
315
```
316
317
### Example 4: JSON Output Processing
318
319
```bash
320
#!/bin/bash
321
# validate-with-json-output.sh - Process JSON validation results
322
323
SCHEMA_FILE="$1"
324
INSTANCE_FILE="$2"
325
326
# Get JSON formatted validation results
327
json_output=$(java -jar json-schema-validator-2.2.6-lib.jar \
328
--json "$SCHEMA_FILE" "$INSTANCE_FILE" 2>/dev/null)
329
exit_code=$?
330
331
if [ $exit_code -eq 0 ]; then
332
echo "Validation successful"
333
else
334
echo "Validation failed. Details:"
335
336
# Use jq to format and extract error information if available
337
if command -v jq >/dev/null 2>&1; then
338
echo "$json_output" | jq -r '.[] | " Error at \(.instance.pointer): \(.message)"'
339
else
340
echo "$json_output"
341
fi
342
fi
343
344
exit $exit_code
345
```
346
347
### Example 5: Custom Reporter Implementation
348
349
```java
350
import com.github.fge.jsonschema.main.cli.Reporter;
351
import com.github.fge.jsonschema.core.report.ProcessingReport;
352
import com.github.fge.jsonschema.core.report.ProcessingMessage;
353
354
/**
355
* Custom reporter that outputs validation results in CSV format
356
*/
357
public class CSVReporter implements Reporter {
358
359
@Override
360
public void reportValidation(ProcessingReport report) throws IOException {
361
System.out.println("Status,Level,Instance,Schema,Message");
362
363
if (report.isSuccess()) {
364
System.out.println("SUCCESS,INFO,,,Validation passed");
365
} else {
366
for (ProcessingMessage message : report) {
367
JsonNode messageJson = message.asJson();
368
String level = message.getLevel().toString();
369
String instancePath = messageJson.path("instance").path("pointer").asText("");
370
String schemaPath = messageJson.path("schema").path("pointer").asText("");
371
String text = message.getMessage().replace(",", ";"); // Escape commas
372
373
System.out.printf("FAILURE,%s,\"%s\",\"%s\",\"%s\"%n",
374
level, instancePath, schemaPath, text);
375
}
376
}
377
}
378
}
379
380
// Usage in custom CLI application
381
public class CustomCLI {
382
public static void main(String[] args) throws Exception {
383
JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
384
JsonNode schema = loadJsonFromFile(args[0]);
385
JsonNode instance = loadJsonFromFile(args[1]);
386
387
JsonSchema jsonSchema = factory.getJsonSchema(schema);
388
ProcessingReport report = jsonSchema.validate(instance);
389
390
Reporter csvReporter = new CSVReporter();
391
csvReporter.reportValidation(report);
392
393
System.exit(report.isSuccess() ? 0 : 100);
394
}
395
}
396
```
397
398
## Maven Integration
399
400
### Using as Build Plugin
401
402
```xml
403
<plugin>
404
<groupId>org.codehaus.mojo</groupId>
405
<artifactId>exec-maven-plugin</artifactId>
406
<version>3.0.0</version>
407
<executions>
408
<execution>
409
<id>validate-schemas</id>
410
<phase>test</phase>
411
<goals>
412
<goal>java</goal>
413
</goals>
414
<configuration>
415
<mainClass>com.github.fge.jsonschema.main.cli.Main</mainClass>
416
<arguments>
417
<argument>${project.basedir}/src/main/resources/schema.json</argument>
418
<argument>${project.basedir}/src/test/resources/test-data.json</argument>
419
</arguments>
420
</configuration>
421
</execution>
422
</executions>
423
</plugin>
424
```
425
426
### Ant Integration
427
428
```xml
429
<target name="validate-json">
430
<java jar="lib/json-schema-validator-2.2.6-lib.jar"
431
fork="true"
432
failonerror="true">
433
<arg value="schemas/api-schema.json"/>
434
<arg value="data/sample-data.json"/>
435
</java>
436
</target>
437
```
438
439
## CLI Best Practices
440
441
1. **Exit Codes**: Always check exit codes in scripts for proper error handling
442
2. **Output Formats**: Use appropriate output formats (brief, JSON) based on your needs
443
3. **Batch Processing**: Validate multiple files efficiently using shell loops
444
4. **Error Handling**: Implement proper error handling and reporting in automation scripts
445
5. **CI Integration**: Include schema validation in continuous integration pipelines
446
6. **Performance**: For large-scale validation, consider programmatic API over CLI
447
7. **Documentation**: Document your validation scripts and their expected behavior