组合值和键以形成 json 对象

Combine values and keys to form json object

我有键和值作为字符串,我需要将它们组合成 json 格式。

例如:我的 "keys" 字符串数组是:{"a","b","c","d"} 我的 "values" 字符串数组我正在通过一个 for 循环,因为它存储在数组 X

X[0], X[1], X[2] and so on..

如何将 "keys""values" 组合成这样:

{ "a":"x","b":"y", "c":"z", "d":"q"
}

我试过迭代和合并,但我卡住了

std::string values="";
std::string keys[4]={"a","b","c","d"};
..
..
..
for(int i=0;i<4;i++)
{
    values= values + "," + x[i];
}

我对如何组合这两个字符串并显示如下所示的结果字符串感到困惑:

{ "a":"x",
  "b":"y",
  "c":"z",
  "d":"q"
}

手动方式可以像这样完成:

std::string res = "{";
std::string keys[4]={"a","b","c","d"};
std::string values[4]={"a","b","c","d"};
const char* sep = "";

for(int i=0;i<4;i++)
{
    res += sep + keys[i] + ":" + values[i];
    sep = ",";
}
res += "}";

使用任何 json 库,您可以执行如下操作:

Json::Value root(Json::ValueType::objectValue);

for (int i = 0; i < 4; i++) {
    root[keys[i]] = values[i];
}

Json::StyledWriter writer;
writer.write(root);