json.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. //
  2. // json.hpp
  3. // json
  4. //
  5. // Created by Sam Jaffe on 1/30/16.
  6. // Copyright © 2016 Sam Jaffe. All rights reserved.
  7. //
  8. #ifndef json_hpp
  9. #define json_hpp
  10. #include <map>
  11. #include <vector>
  12. #include <utility>
  13. #include "../variant/variant.hpp"
  14. #include "json_common.h"
  15. #define JSON_TYPE_LIST \
  16. X(object) \
  17. X(array) \
  18. X(string) \
  19. X(double) \
  20. X(int) \
  21. X(bool)
  22. namespace json {
  23. class value;
  24. namespace parser {
  25. template <typename T> void parse(T& json, char const* data);
  26. template <typename T> void parse(T& json, std::string const& str);
  27. template <typename T> void parse(T& json, std::istream & in);
  28. }
  29. class value {
  30. public:
  31. using object_jt = std::map<std::string, value>;
  32. using array_jt = std::vector<value>;
  33. using string_jt = std::string;
  34. using double_jt = double;
  35. using int_jt = int32_t;
  36. using bool_jt = bool;
  37. private:
  38. static const value null_value;
  39. using data_t = variant<object_jt, array_jt, string_jt, double_jt, int_jt, bool_jt>;
  40. data_t data;
  41. public:
  42. #define X(type) bool is_##type() const { return data.is<type##_jt>(); }
  43. JSON_TYPE_LIST
  44. #undef X
  45. bool is_null() const { return !data.valid(); }
  46. value() = default;
  47. value(value const&) = default;
  48. value(value &&) = default;
  49. value& operator=(value const&) = default;
  50. value& operator=(value &&) = default;
  51. #define X(type) value(type##_jt val) { data.set<type##_jt>(std::move(val)); }
  52. JSON_TYPE_LIST
  53. #undef X
  54. #define X(type) value(type##_jt && val) { data.set<type##_jt>(std::forward<type##_jt>(val)); }
  55. JSON_TYPE_LIST
  56. #undef X
  57. #define X(type) value& operator=(type##_jt val) { data.set<type##_jt>(std::move(val)); return *this; }
  58. JSON_TYPE_LIST
  59. #undef X
  60. void parse(char const* data);
  61. void parse(std::string const& str);
  62. void parse(std::istream & in);
  63. void clear() { data = data_t(); }
  64. value& operator[](const size_t idx);
  65. value const& operator[](const size_t idx) const;
  66. value& operator[](std::string const& key);
  67. value const& operator[](std::string const& key) const;
  68. string_jt const& as_string() const;
  69. double_jt as_double() const;
  70. int_jt as_int() const;
  71. bool_jt as_bool() const;
  72. operator string_jt const&() const { return as_string(); }
  73. operator double_jt() const { return as_double(); }
  74. operator int_jt() const { return as_int(); }
  75. operator bool_jt() const { return as_bool(); }
  76. };
  77. #undef JSON_TYPE_LIST
  78. }
  79. #endif /* json_hpp */