1 //
2 // Copyright (C) 2022 The Android Open Source Project
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 #pragma once
17 
18 #include <string>
19 #include <string_view>
20 #include <vector>
21 
22 #include <json/json.h>
23 
24 #include "common/libs/fs/shared_fd.h"
25 #include "common/libs/utils/result.h"
26 
27 namespace cuttlefish {
28 
29 Result<Json::Value> ParseJson(std::string_view input);
30 
31 Result<Json::Value> LoadFromFile(SharedFD json_fd);
32 Result<Json::Value> LoadFromFile(const std::string& path_to_file);
33 
34 template <typename T>
35 T As(const Json::Value& v);
36 
37 template <>
As(const Json::Value & v)38 inline int As(const Json::Value& v) {
39   return v.asInt();
40 }
41 
42 template <>
As(const Json::Value & v)43 inline std::string As(const Json::Value& v) {
44   return v.asString();
45 }
46 
47 template <>
As(const Json::Value & v)48 inline bool As(const Json::Value& v) {
49   return v.asBool();
50 }
51 
52 template <>
As(const Json::Value & v)53 inline Json::Value As(const Json::Value& v) {
54   return v;
55 }
56 
57 template <typename T>
GetValue(const Json::Value & root,const std::vector<std::string> & selectors)58 Result<T> GetValue(const Json::Value& root,
59                    const std::vector<std::string>& selectors) {
60   const Json::Value* traversal = &root;
61   for (const auto& selector : selectors) {
62     CF_EXPECTF(traversal->isMember(selector),
63                "JSON selector \"{}\" does not exist", selector);
64     traversal = &(*traversal)[selector];
65   }
66   return As<T>(*traversal);
67 }
68 
69 template <typename T>
GetArrayValues(const Json::Value & array,const std::vector<std::string> & selectors)70 Result<std::vector<T>> GetArrayValues(
71     const Json::Value& array, const std::vector<std::string>& selectors) {
72   std::vector<T> result;
73   for (const auto& element : array) {
74     result.emplace_back(CF_EXPECT(GetValue<T>(element, selectors)));
75   }
76   return result;
77 }
78 
HasValue(const Json::Value & root,const std::vector<std::string> & selectors)79 inline bool HasValue(const Json::Value& root,
80                      const std::vector<std::string>& selectors) {
81   const Json::Value* traversal = &root;
82   for (const auto& selector : selectors) {
83     if (!traversal->isMember(selector)) {
84       return false;
85     }
86     traversal = &(*traversal)[selector];
87   }
88   return true;
89 }
90 
91 }  // namespace cuttlefish
92