iopsys-feed/jsonval/src/main.cpp
Sukru Senli a440adbef9 jsonval: 1.0.0
A small CLI tool to validate JSON files against a schema using json-schema-validator and nlohmann/json
2025-06-17 15:38:32 +02:00

64 lines
1.4 KiB
C++

#include <iostream>
#include <fstream>
#include <string>
#include <nlohmann/json.hpp>
#include <nlohmann/json-schema.hpp>
using nlohmann::json;
using nlohmann::json_schema::json_validator;
using namespace std;
void print_usage(const string& prog_name) {
cerr << "Usage: " << prog_name << " -s <schema.json> -j <data.json>" << endl;
}
int main(int argc, char* argv[]) {
string schema_path, data_path;
// Simple argument parsing
for (int i = 1; i < argc; ++i) {
string arg = argv[i];
if ((arg == "-s" || arg == "--schema") && i + 1 < argc) {
schema_path = argv[++i];
} else if ((arg == "-j" || arg == "--json") && i + 1 < argc) {
data_path = argv[++i];
} else {
print_usage(argv[0]);
return 1;
}
}
if (schema_path.empty() || data_path.empty()) {
print_usage(argv[0]);
return 1;
}
ifstream schema_file(schema_path);
ifstream data_file(data_path);
if (!schema_file.is_open() || !data_file.is_open()) {
cerr << "Error: Could not open one or both files." << endl;
return 2;
}
json schema, document;
try {
schema_file >> schema;
data_file >> document;
} catch (const json::parse_error& e) {
cerr << "Parse error: " << e.what() << endl;
return 3;
}
try {
json_validator validator;
validator.set_root_schema(schema);
validator.validate(document);
cout << "Valid" << endl;
} catch (const std::exception& e) {
cerr << "Validation failed: " << e.what() << endl;
return 4;
}
return 0;
}