mirror of
https://github.com/rad4day/Waybar.git
synced 2025-07-13 22:52:30 +02:00
Merge pull request #2496 from zjeffer/tests/json
Fix JSON parsing with hexadecimal characters
This commit is contained in:
@ -3,6 +3,12 @@
|
||||
#include <fmt/ostream.h>
|
||||
#include <json/json.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <codecvt>
|
||||
#include <iostream>
|
||||
#include <locale>
|
||||
#include <regex>
|
||||
|
||||
#if (FMT_VERSION >= 90000)
|
||||
|
||||
template <>
|
||||
@ -12,25 +18,30 @@ struct fmt::formatter<Json::Value> : ostream_formatter {};
|
||||
|
||||
namespace waybar::util {
|
||||
|
||||
struct JsonParser {
|
||||
JsonParser() {}
|
||||
class JsonParser {
|
||||
public:
|
||||
JsonParser() = default;
|
||||
|
||||
const Json::Value parse(const std::string& data) const {
|
||||
Json::Value root(Json::objectValue);
|
||||
if (data.empty()) {
|
||||
return root;
|
||||
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;
|
||||
if (!Json::parseFromStream(m_readerBuilder, jsonStream, &root, &errs)) {
|
||||
throw std::runtime_error("Error parsing JSON: " + errs);
|
||||
}
|
||||
std::unique_ptr<Json::CharReader> const reader(builder_.newCharReader());
|
||||
std::string err;
|
||||
bool res = reader->parse(data.c_str(), data.c_str() + data.size(), &root, &err);
|
||||
if (!res) throw std::runtime_error(err);
|
||||
return root;
|
||||
}
|
||||
|
||||
~JsonParser() = default;
|
||||
|
||||
private:
|
||||
Json::CharReaderBuilder builder_;
|
||||
};
|
||||
Json::CharReaderBuilder m_readerBuilder;
|
||||
|
||||
static std::string replaceHexadecimalEscape(const std::string& str) {
|
||||
static std::regex re("\\\\x");
|
||||
return std::regex_replace(str, re, "\\u00");
|
||||
}
|
||||
};
|
||||
} // namespace waybar::util
|
||||
|
Reference in New Issue
Block a user