json11.hpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. /* json11
  2. *
  3. * json11 is a tiny JSON library for C++11, providing JSON parsing and serialization.
  4. *
  5. * The core object provided by the library is json11::Json. A Json object represents any JSON
  6. * value: null, bool, number (int or double), string (std::string), array (std::vector), or
  7. * object (std::map).
  8. *
  9. * Json objects act like values: they can be assigned, copied, moved, compared for equality or
  10. * order, etc. There are also helper methods Json::dump, to serialize a Json to a string, and
  11. * Json::parse (static) to parse a std::string as a Json object.
  12. *
  13. * Internally, the various types of Json object are represented by the JsonValue class
  14. * hierarchy.
  15. *
  16. * A note on numbers - JSON specifies the syntax of number formatting but not its semantics,
  17. * so some JSON implementations distinguish between integers and floating-point numbers, while
  18. * some don't. In json11, we choose the latter. Because some JSON implementations (namely
  19. * Javascript itself) treat all numbers as the same type, distinguishing the two leads
  20. * to JSON that will be *silently* changed by a round-trip through those implementations.
  21. * Dangerous! To avoid that risk, json11 stores all numbers as double internally, but also
  22. * provides integer helpers.
  23. *
  24. * Fortunately, double-precision IEEE754 ('double') can precisely store any integer in the
  25. * range +/-2^53, which includes every 'int' on most systems. (Timestamps often use int64
  26. * or long long to avoid the Y2038K problem; a double storing microseconds since some epoch
  27. * will be exact for +/- 275 years.)
  28. */
  29. /* Copyright (c) 2013 Dropbox, Inc.
  30. *
  31. * Permission is hereby granted, free of charge, to any person obtaining a copy
  32. * of this software and associated documentation files (the "Software"), to deal
  33. * in the Software without restriction, including without limitation the rights
  34. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  35. * copies of the Software, and to permit persons to whom the Software is
  36. * furnished to do so, subject to the following conditions:
  37. *
  38. * The above copyright notice and this permission notice shall be included in
  39. * all copies or substantial portions of the Software.
  40. *
  41. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  42. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  43. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  44. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  45. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  46. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  47. * THE SOFTWARE.
  48. */
  49. #pragma once
  50. #include <string>
  51. #include <vector>
  52. #include <map>
  53. #include <memory>
  54. #include <initializer_list>
  55. #ifdef _MSC_VER
  56. #if _MSC_VER <= 1800 // VS 2013
  57. #ifndef noexcept
  58. #define noexcept throw()
  59. #endif
  60. #ifndef snprintf
  61. #define snprintf _snprintf_s
  62. #endif
  63. #endif
  64. #endif
  65. namespace json11 {
  66. enum JsonParse {
  67. STANDARD, COMMENTS
  68. };
  69. class JsonValue;
  70. class Json final {
  71. public:
  72. // Types
  73. enum Type {
  74. NUL, NUMBER, BOOL, STRING, ARRAY, OBJECT
  75. };
  76. // Array and object typedefs
  77. typedef std::vector<Json> array;
  78. typedef std::map<std::string, Json> object;
  79. // Constructors for the various types of JSON value.
  80. Json() noexcept; // NUL
  81. Json(std::nullptr_t) noexcept; // NUL
  82. Json(double value); // NUMBER
  83. Json(int value); // NUMBER
  84. Json(bool value); // BOOL
  85. Json(const std::string &value); // STRING
  86. Json(std::string &&value); // STRING
  87. Json(const char * value); // STRING
  88. Json(const array &values); // ARRAY
  89. Json(array &&values); // ARRAY
  90. Json(const object &values); // OBJECT
  91. Json(object &&values); // OBJECT
  92. // Implicit constructor: anything with a to_json() function.
  93. template <class T, class = decltype(&T::to_json)>
  94. Json(const T & t) : Json(t.to_json()) {}
  95. // Implicit constructor: map-like objects (std::map, std::unordered_map, etc)
  96. template <class M, typename std::enable_if<
  97. std::is_constructible<std::string, decltype(std::declval<M>().begin()->first)>::value
  98. && std::is_constructible<Json, decltype(std::declval<M>().begin()->second)>::value,
  99. int>::type = 0>
  100. Json(const M & m) : Json(object(m.begin(), m.end())) {}
  101. // Implicit constructor: vector-like objects (std::list, std::vector, std::set, etc)
  102. template <class V, typename std::enable_if<
  103. std::is_constructible<Json, decltype(*std::declval<V>().begin())>::value,
  104. int>::type = 0>
  105. Json(const V & v) : Json(array(v.begin(), v.end())) {}
  106. // This prevents Json(some_pointer) from accidentally producing a bool. Use
  107. // Json(bool(some_pointer)) if that behavior is desired.
  108. Json(void *) = delete;
  109. // Accessors
  110. Type type() const;
  111. bool is_null() const { return type() == NUL; }
  112. bool is_number() const { return type() == NUMBER; }
  113. bool is_bool() const { return type() == BOOL; }
  114. bool is_string() const { return type() == STRING; }
  115. bool is_array() const { return type() == ARRAY; }
  116. bool is_object() const { return type() == OBJECT; }
  117. // Return the enclosed value if this is a number, 0 otherwise. Note that json11 does not
  118. // distinguish between integer and non-integer numbers - number_value() and int_value()
  119. // can both be applied to a NUMBER-typed object.
  120. double number_value() const;
  121. int int_value() const;
  122. // Return the enclosed value if this is a boolean, false otherwise.
  123. bool bool_value() const;
  124. // Return the enclosed string if this is a string, "" otherwise.
  125. const std::string &string_value() const;
  126. // Return the enclosed std::vector if this is an array, or an empty vector otherwise.
  127. const array &array_items() const;
  128. // Return the enclosed std::map if this is an object, or an empty map otherwise.
  129. const object &object_items() const;
  130. // Return a reference to arr[i] if this is an array, Json() otherwise.
  131. const Json & operator[](size_t i) const;
  132. // Return a reference to obj[key] if this is an object, Json() otherwise.
  133. const Json & operator[](const std::string &key) const;
  134. // Serialize.
  135. void dump(std::string &out) const;
  136. std::string dump() const {
  137. std::string out;
  138. dump(out);
  139. return out;
  140. }
  141. // Parse. If parse fails, return Json() and assign an error message to err.
  142. static Json parse(const std::string & in,
  143. std::string & err,
  144. JsonParse strategy = JsonParse::STANDARD);
  145. static Json parse(const char * in,
  146. std::string & err,
  147. JsonParse strategy = JsonParse::STANDARD) {
  148. if (in) {
  149. return parse(std::string(in), err, strategy);
  150. } else {
  151. err = "null input";
  152. return nullptr;
  153. }
  154. }
  155. // Parse multiple objects, concatenated or separated by whitespace
  156. static std::vector<Json> parse_multi(
  157. const std::string & in,
  158. std::string::size_type & parser_stop_pos,
  159. std::string & err,
  160. JsonParse strategy = JsonParse::STANDARD);
  161. static inline std::vector<Json> parse_multi(
  162. const std::string & in,
  163. std::string & err,
  164. JsonParse strategy = JsonParse::STANDARD) {
  165. std::string::size_type parser_stop_pos;
  166. return parse_multi(in, parser_stop_pos, err, strategy);
  167. }
  168. bool operator== (const Json &rhs) const;
  169. bool operator< (const Json &rhs) const;
  170. bool operator!= (const Json &rhs) const { return !(*this == rhs); }
  171. bool operator<= (const Json &rhs) const { return !(rhs < *this); }
  172. bool operator> (const Json &rhs) const { return (rhs < *this); }
  173. bool operator>= (const Json &rhs) const { return !(*this < rhs); }
  174. /* has_shape(types, err)
  175. *
  176. * Return true if this is a JSON object and, for each item in types, has a field of
  177. * the given type. If not, return false and set err to a descriptive message.
  178. */
  179. typedef std::initializer_list<std::pair<std::string, Type>> shape;
  180. bool has_shape(const shape & types, std::string & err) const;
  181. private:
  182. std::shared_ptr<JsonValue> m_ptr;
  183. };
  184. // Internal class hierarchy - JsonValue objects are not exposed to users of this API.
  185. class JsonValue {
  186. protected:
  187. friend class Json;
  188. friend class JsonInt;
  189. friend class JsonDouble;
  190. virtual Json::Type type() const = 0;
  191. virtual bool equals(const JsonValue * other) const = 0;
  192. virtual bool less(const JsonValue * other) const = 0;
  193. virtual void dump(std::string &out) const = 0;
  194. virtual double number_value() const;
  195. virtual int int_value() const;
  196. virtual bool bool_value() const;
  197. virtual const std::string &string_value() const;
  198. virtual const Json::array &array_items() const;
  199. virtual const Json &operator[](size_t i) const;
  200. virtual const Json::object &object_items() const;
  201. virtual const Json &operator[](const std::string &key) const;
  202. virtual ~JsonValue() {}
  203. };
  204. } // namespace json11