json.hpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. #pragma once
  9. #include "variant/variant.hpp"
  10. #include "json_common.hpp"
  11. #include <map>
  12. #include <vector>
  13. #include <utility>
  14. #define JSON_TYPE_LIST \
  15. X(object) \
  16. X(array) \
  17. X(string) \
  18. X(double) \
  19. X(int) \
  20. X(uint) \
  21. X(bool)
  22. namespace json {
  23. class value;
  24. template <>
  25. void helper::parse_numeric(value & json, char const * & data);
  26. namespace parser {
  27. void parse(value&, char const*);
  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 = json::string_jt;
  34. using double_jt = json::double_jt;
  35. using int_jt = json::int_jt;
  36. using uint_jt = json::uint_jt;
  37. using bool_jt = json::bool_jt;
  38. private:
  39. static const value null_value;
  40. using data_t = variant<object_jt, array_jt, string_jt, double_jt, int_jt, uint_jt, bool_jt>;
  41. data_t data;
  42. public:
  43. #define X(type) bool is_##type() const { return data.is<type##_jt>(); }
  44. JSON_TYPE_LIST
  45. #undef X
  46. bool is_null() const { return !data.valid(); }
  47. value() = default;
  48. value(value const&) = default;
  49. value(value &&) = default;
  50. value& operator=(value const&) = default;
  51. value& operator=(value &&) = default;
  52. #define X(type) value(type##_jt val) { data.set<type##_jt>(std::move(val)); }
  53. JSON_TYPE_LIST
  54. #undef X
  55. #define X(type) value& operator=(type##_jt val) { data.set<type##_jt>(std::move(val)); return *this; }
  56. JSON_TYPE_LIST
  57. #undef X
  58. void parse(char const* data);
  59. void parse(std::string const& str);
  60. void parse(std::istream & in);
  61. void clear() { data = data_t(); }
  62. value& operator[](const size_t idx);
  63. value const& operator[](const size_t idx) const;
  64. value& operator[](std::string const& key);
  65. value const& operator[](std::string const& key) const;
  66. string_jt const& as_string() const;
  67. double_jt as_double() const;
  68. int_jt as_int() const;
  69. uint_jt as_uint() const;
  70. bool_jt as_bool() const;
  71. operator string_jt const&() const { return as_string(); }
  72. operator double_jt() const { return as_double(); }
  73. operator int_jt() const { return as_int(); }
  74. operator uint_jt() const { return as_uint(); }
  75. operator bool_jt() const { return as_bool(); }
  76. };
  77. #undef JSON_TYPE_LIST
  78. namespace parser {
  79. void parse(json::value &, char const *);
  80. void parse(json::value& json, std::istream & in);
  81. }
  82. }