json.hpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include <sstream>
  2. #include <type_traits>
  3. #include "hexxer.hpp"
  4. template <typename R>
  5. auto hexify (const R& range) {
  6. std::stringstream ss;
  7. for (auto& x : range) {
  8. ss << hexxer::encodeFirst(x) << hexxer::encodeSecond(x);
  9. }
  10. return ss.str();
  11. }
  12. auto jsonify (const std::string& v) {
  13. return "\"" + v + "\"";
  14. }
  15. template <typename R>
  16. std::enable_if_t<std::is_same<typename R::value_type, uint8_t>::value, std::string>
  17. jsonify (const R& r) {
  18. return jsonify(hexify<R>(r));
  19. }
  20. auto jsonp (const std::string& k, const std::string& v) {
  21. std::stringstream ss;
  22. ss << "\"" << k << "\": " << v;
  23. return ss.str();
  24. }
  25. auto jsonify (const bool v) {
  26. return v ? "true" : "false";
  27. }
  28. template <char L = ' ', char R = ' ', typename Range, typename F>
  29. auto jsonify_csv (const Range r, F f) {
  30. std::stringstream ss;
  31. size_t i = 0;
  32. if (L != ' ') ss << L;
  33. for (const auto& x : r) {
  34. const auto fx = f(x);
  35. if (fx.empty()) continue;
  36. if (i++ > 0) ss << ',';
  37. ss << fx;
  38. }
  39. if (R != ' ') ss << R;
  40. return ss.str();
  41. }
  42. auto json_identity (const std::string& s) { return s; }
  43. template <typename R = std::initializer_list<std::string>, typename F = decltype(json_identity)>
  44. auto jsonifyO (const R& r, F f = json_identity) {
  45. return jsonify_csv<'{', '}'>(r, f);
  46. }
  47. template <typename R = std::initializer_list<std::string>, typename F = decltype(json_identity)>
  48. auto jsonifyA (const R& r, F f = json_identity) {
  49. return jsonify_csv<'[', ']'>(r, f);
  50. }