2018-08-13 19:23:43 +00:00
|
|
|
#pragma once
|
|
|
|
|
2022-07-12 05:52:33 +00:00
|
|
|
#include <fmt/ostream.h>
|
2018-08-13 19:23:43 +00:00
|
|
|
#include <json/json.h>
|
|
|
|
|
2023-09-10 18:36:27 +00:00
|
|
|
#include <algorithm>
|
|
|
|
#include <codecvt>
|
|
|
|
#include <iostream>
|
|
|
|
#include <locale>
|
|
|
|
#include <regex>
|
|
|
|
|
2022-07-12 05:52:33 +00:00
|
|
|
#if (FMT_VERSION >= 90000)
|
|
|
|
|
|
|
|
template <>
|
|
|
|
struct fmt::formatter<Json::Value> : ostream_formatter {};
|
|
|
|
|
|
|
|
#endif
|
|
|
|
|
2018-08-13 19:23:43 +00:00
|
|
|
namespace waybar::util {
|
|
|
|
|
2023-09-10 18:36:27 +00:00
|
|
|
class JsonParser {
|
|
|
|
public:
|
|
|
|
JsonParser() = default;
|
|
|
|
|
|
|
|
Json::Value parse(const std::string& jsonStr) {
|
|
|
|
Json::Value root;
|
2018-08-18 15:54:20 +00:00
|
|
|
|
2023-09-10 18:36:27 +00:00
|
|
|
// replace all occurrences of "\x" with "\u00", because JSON doesn't allow "\x" escape sequences
|
|
|
|
std::string modifiedJsonStr = replaceHexadecimalEscape(jsonStr);
|
|
|
|
|
|
|
|
std::istringstream jsonStream(modifiedJsonStr);
|
|
|
|
std::string errs;
|
|
|
|
if (!Json::parseFromStream(m_readerBuilder, jsonStream, &root, &errs)) {
|
|
|
|
throw std::runtime_error("Error parsing JSON: " + errs);
|
2019-04-18 15:43:16 +00:00
|
|
|
}
|
2018-08-18 15:54:20 +00:00
|
|
|
return root;
|
|
|
|
}
|
|
|
|
|
2019-04-18 15:52:00 +00:00
|
|
|
private:
|
2023-09-10 18:36:27 +00:00
|
|
|
Json::CharReaderBuilder m_readerBuilder;
|
2018-08-13 19:23:43 +00:00
|
|
|
|
2023-09-10 18:36:27 +00:00
|
|
|
static std::string replaceHexadecimalEscape(const std::string& str) {
|
|
|
|
static std::regex re("\\\\x");
|
|
|
|
return std::regex_replace(str, re, "\\u00");
|
|
|
|
}
|
|
|
|
};
|
2019-04-18 15:52:00 +00:00
|
|
|
} // namespace waybar::util
|