xref: /openbmc/bmcweb/redfish-core/src/utils/json_utils.cpp (revision 40e9b92ec19acffb46f83a6e55b18974da5d708e)
1 // SPDX-License-Identifier: Apache-2.0
2 // SPDX-FileCopyrightText: Copyright OpenBMC Authors
3 // SPDX-FileCopyrightText: Copyright 2018 Intel Corporation
4 #include "utils/json_utils.hpp"
5 
6 #include "error_messages.hpp"
7 #include "http/http_request.hpp"
8 #include "http/http_response.hpp"
9 #include "http/parsing.hpp"
10 
11 #include <nlohmann/json.hpp>
12 
13 #include <cstdint>
14 #include <string>
15 
16 namespace redfish
17 {
18 
19 namespace json_util
20 {
21 
processJsonFromRequest(crow::Response & res,const crow::Request & req,nlohmann::json & reqJson)22 bool processJsonFromRequest(crow::Response& res, const crow::Request& req,
23                             nlohmann::json& reqJson)
24 {
25     JsonParseResult ret = parseRequestAsJson(req, reqJson);
26     if (ret == JsonParseResult::BadContentType)
27     {
28         messages::unrecognizedRequestBody(res);
29         return false;
30     }
31     reqJson = nlohmann::json::parse(req.body(), nullptr, false);
32 
33     if (reqJson.is_discarded())
34     {
35         messages::malformedJSON(res);
36         return false;
37     }
38 
39     return true;
40 }
41 
getEstimatedJsonSize(const nlohmann::json & root)42 uint64_t getEstimatedJsonSize(const nlohmann::json& root)
43 {
44     if (root.is_null())
45     {
46         return 4;
47     }
48     if (root.is_number())
49     {
50         return 8;
51     }
52     if (root.is_boolean())
53     {
54         return 5;
55     }
56     if (root.is_string())
57     {
58         constexpr uint64_t quotesSize = 2;
59         return root.get<std::string>().size() + quotesSize;
60     }
61     if (root.is_binary())
62     {
63         return root.get_binary().size();
64     }
65     const nlohmann::json::array_t* arr =
66         root.get_ptr<const nlohmann::json::array_t*>();
67     if (arr != nullptr)
68     {
69         uint64_t sum = 0;
70         for (const auto& element : *arr)
71         {
72             sum += getEstimatedJsonSize(element);
73         }
74         return sum;
75     }
76     const nlohmann::json::object_t* object =
77         root.get_ptr<const nlohmann::json::object_t*>();
78     if (object != nullptr)
79     {
80         uint64_t sum = 0;
81         for (const auto& [k, v] : *object)
82         {
83             constexpr uint64_t colonQuoteSpaceSize = 4;
84             sum += k.size() + getEstimatedJsonSize(v) + colonQuoteSpaceSize;
85         }
86         return sum;
87     }
88     return 0;
89 }
90 
91 } // namespace json_util
92 } // namespace redfish
93