ZBLOG

使用类似void jsonToYaml(const json& jsonData, YAML::Emitter& emitter) { if (jsonData.is_object()) { emitter

您提供的代码看起来是使用 nlohmann/json 库和 yaml-cpp 库进行 JSON 到 YAML 的转换。这个递归函数 jsonToYaml 接受一个 json 对象和一个 YAML::Emitter,将 JSON 转换为对应的 YAML。

下面是完整示例代码:

  1. #include <iostream>
  2. #include <fstream>
  3. #include <yaml-cpp/yaml.h>
  4. #include <nlohmann/json.hpp>
  5. using json = nlohmann::json;
  6. void jsonToYaml(const json& jsonData, YAML::Emitter& emitter)
  7. {
  8. if (jsonData.is_object())
  9. {
  10. emitter << YAML::BeginMap;
  11. for (auto it = jsonData.begin(); it != jsonData.end(); ++it)
  12. {
  13. emitter << YAML::Key << it.key();
  14. jsonToYaml(it.value(), emitter);
  15. }
  16. emitter << YAML::EndMap;
  17. }
  18. else if (jsonData.is_array())
  19. {
  20. emitter << YAML::BeginSeq;
  21. for (const auto& item : jsonData)
  22. {
  23. jsonToYaml(item, emitter);
  24. }
  25. emitter << YAML::EndSeq;
  26. }
  27. else
  28. {
  29. // Scalar value
  30. emitter << jsonData.get<json::string_t>();
  31. }
  32. }
  33. int main()
  34. {
  35. json jsonData = R"(
  36. {
  37. "name": "全府员公多市面",
  38. "applications": 1,
  39. "notes": "laborum",
  40. "generate": [
  41. {
  42. "incentive_id": 1,
  43. "node_id": 1,
  44. "data_struct_number": "74"
  45. }
  46. ]
  47. })"_json;
  48. YAML::Emitter yamlEmitter;
  49. jsonToYaml(jsonData, yamlEmitter);
  50. std::ofstream file("output.yaml");
  51. file << yamlEmitter.c_str();
  52. file.close();
  53. return 0;
  54. }

请确保在编译时链接并包含所需的库,yaml-cpp 和 nlohmann/json。以上示例代码将 JSON 数据转换为 YAML,并将结果写入到 output.yaml 文件中。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?