[db2] Load from json.

This commit is contained in:
lzwdgc 2024-04-02 23:58:13 +03:00
parent c4e42dea25
commit 21a14caf12
2 changed files with 32 additions and 6 deletions

View file

@ -207,6 +207,25 @@ struct db2 {
} }
return ja; return ja;
} }
void load_from_json(const path &fn) {
auto ja = nlohmann::json::parse(read_file(fn));
for (auto &&[tn,t] : ja.items()) {
for (auto &&[vn,v] : t.items()) {
for (auto &&[fn, fv] : v.items()) {
if (0) {
} else if (fv.is_number_integer()) {
m[tn][vn][fn] = fv.get<int>();
} else if (fv.is_number_float()) {
m[tn][vn][fn] = fv.get<float>();
} else if (fv.is_string()) {
m[tn][vn][fn] = fv.get<std::string>();
} else {
throw std::runtime_error{"bad json type"};
}
}
}
}
}
void save(const path &fn, int codepage = 1251) { void save(const path &fn, int codepage = 1251) {
auto s_to_char20 = [&](char20 &dst, const std::string &in, int codepage = 1251) { auto s_to_char20 = [&](char20 &dst, const std::string &in, int codepage = 1251) {
auto s = utf8_to_dbstr(in); auto s = utf8_to_dbstr(in);

View file

@ -31,15 +31,22 @@
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
cl::opt<path> db_fn(cl::Positional, cl::desc("<db file>"), cl::Required); cl::opt<path> db_fn(cl::Positional, cl::desc("<db file or json file to backwards conversion>"), cl::Required);
cl::ParseCommandLineOptions(argc, argv); cl::ParseCommandLineOptions(argc, argv);
db2 db{db_fn}; path fn = db_fn;
auto f = db.open(); fn = fs::absolute(fn);
auto m = f.to_map(); if (fn.extension() != ".json") {
write_file(path{db_fn} += ".json", m.to_json().dump(1)); db2 db{fn};
m.save(path{db_fn} += "new"); auto f = db.open();
auto m = f.to_map();
write_file(path{fn} += ".json", m.to_json().dump(1));
} else {
db2::files::db2_internal db;
db.load_from_json(fn);
db.save(fn.parent_path() / fn.stem());
}
return 0; return 0;
} }