• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 #ifndef MINDSPORE_CCSRC_DISTRIBUTED_PERSISTENT_STORAGE_JSON_UTILS_H_
18 #define MINDSPORE_CCSRC_DISTRIBUTED_PERSISTENT_STORAGE_JSON_UTILS_H_
19 
20 #include <fstream>
21 #include <string>
22 
23 #include "include/common/utils/json_operation_utils.h"
24 #include "nlohmann/json.hpp"
25 
26 namespace mindspore {
27 namespace distributed {
28 namespace storage {
29 // This class uses json format to store and obtain a large number of key-value pairs, supports creating or opening json
30 // files, reading or modifying key-value in json.
31 class JsonUtils {
32  public:
JsonUtils(const std::string & file_name)33   explicit JsonUtils(const std::string &file_name) : file_name_(file_name) {}
34   ~JsonUtils() = default;
35 
36   // Load or create a json file.
37   bool Initialize();
38 
39   // Get the value corresponding to the key in json.
40   template <typename T>
41   T Get(const std::string &key) const;
42 
43   // Insert a key-value pair into json or change the value corresponding to the key in json.
44   template <typename T>
45   void Insert(const std::string &key, const T &value);
46 
47   // Check whether key exists in json or not.
48   bool Exists(const std::string &key) const;
49 
50  private:
51   // Json object.
52   nlohmann::json js_;
53 
54   // The json file path.
55   std::string file_name_;
56 };
57 
58 template <typename T>
Get(const std::string & key)59 T JsonUtils::Get(const std::string &key) const {
60   if (!js_.contains(key)) {
61     MS_LOG(EXCEPTION) << "The key:" << key << " is not exist.";
62   }
63 
64   return GetJsonValue<T>(js_, key);
65 }
66 
67 template <typename T>
Insert(const std::string & key,const T & value)68 void JsonUtils::Insert(const std::string &key, const T &value) {
69   std::ofstream output_file(file_name_);
70   js_[key] = value;
71   output_file << js_.dump();
72   output_file.close();
73 }
74 }  // namespace storage
75 }  // namespace distributed
76 }  // namespace mindspore
77 
78 #endif  // MINDSPORE_CCSRC_DISTRIBUTED_PERSISTENT_STORAGE_JSON_UTILS_H_
79