请帮我写一段代码。 nlohmann::json怎么把三个字典合并到一起,c++ 14标准,并且每个字典的长度不一样,原数据不是json。 例如:
data1 = [{"key1": "a1", "key2": 1}, {"key1": "a2", "key2": 2}]
data2 = [{"key3": "b1",}, {"key3": "b1",}]
data3 = [{"key4": "cc", "key5": 5, "key6": 1.01},{"key4": "cc", "key5": 5, "key6": 1.01}]
最终想要的数据:
data = [
{"key1": "a1", "key2": 1, "key3": "b1", "key4": "cc", "key5": 5, "key6": 1.01},
{"key1": "a1", "key2": 1, "key3": "b1", "key4": "cc", "key5": 5, "key6": 1.01},
]
#include <iostream> #include <vector> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // 创建原始数据 std::vector<std::map<std::string, json>> data1 = { {{"key1", "a1"}, {"key2", 1}}, {{"key1", "a2"}, {"key2", 2}} }; std::vector<std::map<std::string, json>> data2 = { {{"key3", "b1"}}, {{"key3", "b1"}} }; std::vector<std::map<std::string, json>> data3 = { {{"key4", "cc"}, {"key5", 5}, {"key6", 1.01}}, {{"key4", "cc"}, {"key5", 5}, {"key6", 1.01}} }; // 创建结果容器 std::vector<std::map<std::string, json>> mergedData; // 合并数据 for (size_t i = 0; i < data1.size(); ++i) { std::map<std::string, json> mergedItem; mergedItem.insert(data1[i].begin(), data1[i].end()); mergedItem.insert(data2[i].begin(), data2[i].end()); mergedItem.insert(data3[i].begin(), data3[i].end()); mergedData.push_back(mergedItem); } // 转换为 nlohmann::json 对象 json jsonData = mergedData; // 打印最终结果 std::cout << jsonData.dump() << std::endl; return 0; }
标签:map,key3,key2,key1,横向,c++,key6,key5,key4 From: https://www.cnblogs.com/renfanzi/p/17454760.html