File: json.hpp

package info (click to toggle)
waybar 0.15.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,464 kB
  • sloc: cpp: 25,331; xml: 742; python: 146; ansic: 77; makefile: 29
file content (48 lines) | stat: -rw-r--r-- 1,222 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#pragma once

#include <fmt/ostream.h>
#include <json/json.h>

#include <algorithm>
#include <codecvt>
#include <iostream>
#include <locale>
#include <regex>

#if (FMT_VERSION >= 90000)

template <>
struct fmt::formatter<Json::Value> : ostream_formatter {};

#endif

namespace waybar::util {

class JsonParser {
 public:
  JsonParser() = default;

  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;
  }

 private:
  static std::string replaceHexadecimalEscape(const std::string& str) {
    static std::regex re("\\\\x");
    return std::regex_replace(str, re, "\\u00");
  }
};
}  // namespace waybar::util