组合值和键以形成json对象

时间:2019-05-22 06:42:42

标签: c++ json httpserver jsoncpp

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

例如:我的"keys"字符串数组是:{"a","b","c","d"} 我的"values"字符串数组正在存储在数组X

中,因此正在经历for循环
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"
}

1 个答案:

答案 0 :(得分:1)

可以通过以下方式完成手动操作:

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);