From 4c5dbd4b7cbf81f96305a96b90e57448cfed4470 Mon Sep 17 00:00:00 2001 From: WarmUpTill <19472752+WarmUpTill@users.noreply.github.com> Date: Thu, 17 Apr 2025 11:36:05 +0200 Subject: [PATCH] Add more JSON helpers --- CMakeLists.txt | 15 ++++++++++++++ lib/utils/json-helpers.cpp | 42 ++++++++++++++++++++++++++++++++++++++ lib/utils/json-helpers.hpp | 4 ++++ 3 files changed, 61 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index bda194d0..2bdbd461 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -360,6 +360,21 @@ else() endif() target_link_libraries(${LIB_NAME} PUBLIC nlohmann_json::nlohmann_json) +if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/deps/jsoncons/CMakeLists.txt") + # Don't build jsoncons unit tests as they are causing compilation issues and + # won't be executed either way + if(OS_MACOS) + cmake_policy(SET CMP0077 NEW) + endif() + set(JSONCONS_BUILD_TESTS + OFF + CACHE BOOL "" FORCE) + + add_subdirectory(deps/jsoncons) + target_link_libraries(${LIB_NAME} PRIVATE jsoncons) + target_compile_definitions(${LIB_NAME} PRIVATE JSONPATH_SUPPORT=1) +endif() + find_package(CURL QUIET) find_package(Libcurl QUIET) if(CURL_FOUND) diff --git a/lib/utils/json-helpers.cpp b/lib/utils/json-helpers.cpp index 9c21e3cc..1ca8486b 100644 --- a/lib/utils/json-helpers.cpp +++ b/lib/utils/json-helpers.cpp @@ -1,5 +1,9 @@ #include "json-helpers.hpp" +#ifdef JSONPATH_SUPPORT +#include +#include +#endif #include #include @@ -57,4 +61,42 @@ std::optional GetJsonField(const std::string &jsonStr, return {}; } +std::optional QueryJson(const std::string &jsonStr, + const std::string &query) +{ +#ifdef JSONPATH_SUPPORT + try { + auto json = jsoncons::json::parse(jsonStr); + auto result = jsoncons::jsonpath::json_query(json, query); + return result.as_string(); + } catch (const jsoncons::json_exception &) { + return {}; + } catch (const jsoncons::json_errc &) { + return {}; + } +#else + return {}; +#endif +} + +std::optional AccessJsonArrayIndex(const std::string &jsonStr, + const int index) +{ + try { + nlohmann::json json = nlohmann::json::parse(jsonStr); + if (!json.is_array() || index >= (int)json.size() || + index < 0) { + return {}; + } + auto result = json.at(index); + if (result.is_string()) { + return result.get(); + } + return result.dump(); + } catch (const nlohmann::json::exception &) { + return {}; + } + return {}; +} + } // namespace advss diff --git a/lib/utils/json-helpers.hpp b/lib/utils/json-helpers.hpp index f7a82771..0ac90993 100644 --- a/lib/utils/json-helpers.hpp +++ b/lib/utils/json-helpers.hpp @@ -13,5 +13,9 @@ EXPORT bool MatchJson(const std::string &json1, const std::string &json2, const RegexConfig ®ex); EXPORT std::optional GetJsonField(const std::string &json, const std::string &id); +EXPORT std::optional QueryJson(const std::string &json, + const std::string &query); +EXPORT std::optional AccessJsonArrayIndex(const std::string &json, + const int index); } // namespace advss