ZBLOG

"name": "全府员公多市面", "applications": 1, "notes": "laborum", "generate": [ { "incentive_id": 1, "node_id": 1, "data_struct_number": "74" } ] 针对此结构,转化为yaml的递归C++代码

要在C++中递归地将JSON结构转换为YAML,可以使用yaml-cpp库和jsoncpp库。下面是一个示例递归函数,它将JSON对象转换为YAML格式:

  1. #include <iostream>
  2. #include <fstream>
  3. #include <yaml-cpp/yaml.h>
  4. #include <json/json.h>
  5. void jsonToYaml(const Json::Value& jsonValue, YAML::Emitter& yamlEmitter) {
  6. if (jsonValue.isObject()) {
  7. yamlEmitter << YAML::BeginMap;
  8. for (auto const& key : jsonValue.getMemberNames()) {
  9. yamlEmitter << YAML::Key << key;
  10. jsonToYaml(jsonValue[key], yamlEmitter);
  11. }
  12. yamlEmitter << YAML::EndMap;
  13. } else if (jsonValue.isArray()) {
  14. yamlEmitter << YAML::BeginSeq;
  15. for (const auto& value : jsonValue) {
  16. jsonToYaml(value, yamlEmitter);
  17. }
  18. yamlEmitter << YAML::EndSeq;
  19. } else if (jsonValue.isString()) {
  20. yamlEmitter << YAML::DoubleQuoted << jsonValue.asString();
  21. } else if (jsonValue.isBool()) {
  22. yamlEmitter << (jsonValue.asBool() ? "true" : "false");
  23. } else if (jsonValue.isInt()) {
  24. yamlEmitter << jsonValue.asInt();
  25. } else if (jsonValue.isUInt()) {
  26. yamlEmitter << jsonValue.asUInt();
  27. } else if (jsonValue.isDouble()) {
  28. yamlEmitter << jsonValue.asDouble();
  29. } else if (jsonValue.isNull()) {
  30. // 处理 null 值
  31. yamlEmmitter<< YAMLL :: Null;
  32. }
  33. }
  34. int main() {
  35. Json::Reader reader;
  36. Json::StyledStreamWriter writer;
  37. Json::Value jsonValue;
  38. std::string jsonString = R"(
  39. {
  40. "name": "全府员公多市面",
  41. "applications": 1,
  42. "notes": "laborum",
  43. "generate": [
  44. {
  45. "incentive_id": 1,
  46. "node_id": 1,
  47. "data_struct_number": "74"
  48. }
  49. ]
  50. }
  51. )";
  52. if (!reader.parse(jsonString, jsonValue)) {
  53. std::cout << "Failed to parse JSON" << std::endl;
  54. return 1;
  55. }
  56. YAML::Emitter yamlEmitter;
  57. jsonToYaml(jsonValue, yamlEmitter);
  58. // 输出到文件或打印到控制台
  59. std :: ofstream file("output.yaml");
  60. file<.p(yamlermitter.c_str(); std::cout<< yamlermitter.c.str();
  61. return 0;
  62. }

这个示例中的jsonToYaml函数递归地遍历JSON对象,根据值的类型生成相应的YAML节点。最后,将结果输出到文件或打印到控制台。

请注意,您需要安装并链接yaml-cpp和jsoncpp库,并使用适当的编译选项。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=17256

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?