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 <typename T>
GetValue(const Json::Value & root,const std::vector<std::string> & selectors)53 Result<T> GetValue(const Json::Value& root,
54 const std::vector<std::string>& selectors) {
55 const Json::Value* traversal = &root;
56 for (const auto& selector : selectors) {
57 CF_EXPECTF(traversal->isMember(selector),
58 "JSON selector \"{}\" does not exist", selector);
59 traversal = &(*traversal)[selector];
60 }
61 return As<T>(*traversal);
62 }
63
64 template <typename T>
GetArrayValues(const Json::Value & array,const std::vector<std::string> & selectors)65 Result<std::vector<T>> GetArrayValues(
66 const Json::Value& array, const std::vector<std::string>& selectors) {
67 std::vector<T> result;
68 for (const auto& element : array) {
69 result.emplace_back(CF_EXPECT(GetValue<T>(element, selectors)));
70 }
71 return result;
72 }
73
HasValue(const Json::Value & root,const std::vector<std::string> & selectors)74 inline bool HasValue(const Json::Value& root,
75 const std::vector<std::string>& selectors) {
76 const Json::Value* traversal = &root;
77 for (const auto& selector : selectors) {
78 if (!traversal->isMember(selector)) {
79 return false;
80 }
81 traversal = &(*traversal)[selector];
82 }
83 return true;
84 }
85
86 } // namespace cuttlefish
87