You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

serdes.cc 1.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * Copyright 2021 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "minddata/dataset/engine/serdes.h"
  17. namespace mindspore {
  18. namespace dataset {
  19. Status Serdes::SaveToJSON(std::shared_ptr<DatasetNode> node, const std::string &filename, nlohmann::json *out_json) {
  20. // Dump attributes of current node to json string
  21. nlohmann::json args;
  22. RETURN_IF_NOT_OK(node->to_json(&args));
  23. args["op_type"] = node->Name();
  24. // If the current node isn't leaf node, visit all its children and get all attributes
  25. std::vector<nlohmann::json> children_pipeline;
  26. if (!node->IsLeaf()) {
  27. for (auto child : node->Children()) {
  28. nlohmann::json child_args;
  29. RETURN_IF_NOT_OK(SaveToJSON(child, "", &child_args));
  30. children_pipeline.push_back(child_args);
  31. }
  32. }
  33. args["children"] = children_pipeline;
  34. // Save json string into file if filename is given.
  35. if (!filename.empty()) {
  36. RETURN_IF_NOT_OK(SaveJSONToFile(args, filename));
  37. }
  38. *out_json = args;
  39. return Status::OK();
  40. }
  41. Status Serdes::SaveJSONToFile(nlohmann::json json_string, const std::string &file_name) {
  42. try {
  43. std::ofstream file(file_name);
  44. file << json_string;
  45. } catch (const std::exception &err) {
  46. RETURN_STATUS_UNEXPECTED("Save json string into " + file_name + " failed!");
  47. }
  48. return Status::OK();
  49. }
  50. } // namespace dataset
  51. } // namespace mindspore