Files

49 lines
1.2 KiB
C++
Raw Permalink Normal View History

2018-08-13 21:23:43 +02:00
#pragma once
2022-07-11 22:52:33 -07:00
#include <fmt/ostream.h>
2018-08-13 21:23:43 +02:00
#include <json/json.h>
#include <algorithm>
#include <codecvt>
#include <iostream>
#include <locale>
#include <regex>
2022-07-11 22:52:33 -07:00
#if (FMT_VERSION >= 90000)
template <>
struct fmt::formatter<Json::Value> : ostream_formatter {};
#endif
2018-08-13 21:23:43 +02:00
namespace waybar::util {
class JsonParser {
public:
JsonParser() = default;
2018-08-13 21:23:43 +02:00
Json::Value parse(const std::string& jsonStr) {
Json::Value root;
// 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;
// Use local CharReaderBuilder for thread safety - the IPC singleton's
// parser can be called concurrently from multiple module threads
Json::CharReaderBuilder readerBuilder;
if (!Json::parseFromStream(readerBuilder, jsonStream, &root, &errs)) {
throw std::runtime_error("Error parsing JSON: " + errs);
}
return root;
}
2018-08-13 21:23:43 +02:00
2019-04-18 17:52:00 +02:00
private:
static std::string replaceHexadecimalEscape(const std::string& str) {
static std::regex re("\\\\x");
return std::regex_replace(str, re, "\\u00");
}
};
2019-04-18 17:52:00 +02:00
} // namespace waybar::util