json.hpp是一个非常强大的工具,只需要包含这个头文件,即可对json文件进行操作。
Git地址:GitHub - nlohmann/json: JSON for Modern C++
Git上有简单的使用说明,简书这位作者已经将其汉化。
主要使用到了其中的打补丁的功能,将两个不同的json比较,先把不同的部分区分出来成为patch,然后打在指定的json中。
#include "json.hpp"
#include <iostream>
#include <iomanip>
#include <fstream>
#include<iomanip>
using json = nlohmann::json;
bool readJson(json &jsonData,const std::string& fname){
std::ifstream ifs(fname,std::fstream::in);
try {
ifs >> jsonData;
} catch (std::exception &e) {
std::cout<<"["<<__FUNCTION__<<"]"<<e.what()<<"\n";
ifs.close();
return false;
}
ifs.close();
return true;
}
void jsonHandle(int argc, char *argv[])
{
if(argc < 3){
printf( "Usage: %s [source.json] [target.json]\n", argv[0] );
}else{
printf("Input: source:%s, target:%s\n",argv[1], argv[2]);
}
json j_origin;
if(!readJson(j_origin, argv[1]))
printf("Read json file error!\n");
json j_target;
if(!readJson(j_target, argv[2]))
printf("Read json file error!\n");
json j_patch = json::diff(j_origin, j_target);
json j_result = j_origin.patch(j_patch);
std::ofstream ofs(argv[1], std::fstream::out);
ofs << std::setw(4) << j_result << std::endl;
ofs.close();
}
int main(int argc, char *argv[])
{
jsonHandle(argc, argv);
return 0;
}
编译完成即为一个小工具。