You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

251 lines
9.4 KiB

  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. {
  68. STANDARD, COMMENTS
  69. };
  70. class JsonValue;
  71. class Json final
  72. {
  73. public:
  74. // Types
  75. enum Type
  76. {
  77. NUL, NUMBER, BOOL, STRING, ARRAY, OBJECT
  78. };
  79. // Array and object typedefs
  80. typedef std::vector<Json> array;
  81. typedef std::map<std::string, Json> object;
  82. // Constructors for the various types of JSON value.
  83. Json() noexcept; // NUL
  84. Json( std::nullptr_t ) noexcept; // NUL
  85. Json( double value ); // NUMBER
  86. Json( int value ); // NUMBER
  87. Json( bool value ); // BOOL
  88. Json( const std::string& value ); // STRING
  89. Json( std::string&& value ); // STRING
  90. Json( const char* value ); // STRING
  91. Json( const array& values ); // ARRAY
  92. Json( array&& values ); // ARRAY
  93. Json( const object& values ); // OBJECT
  94. Json( object&& values ); // OBJECT
  95. // Implicit constructor: anything with a to_json() function.
  96. template <class T, class = decltype(& T::to_json)>
  97. Json( const T& t ) : Json( t.to_json() ) {}
  98. // Implicit constructor: map-like objects (std::map, std::unordered_map, etc)
  99. template <class M, typename std::enable_if<
  100. std::is_constructible<std::string,
  101. decltype(std::declval<M>().begin()->first)>::value
  102. && std::is_constructible<Json,
  103. decltype(std::declval<M>().begin()->second)>::value,
  104. int>::type = 0>
  105. Json( const M& m ) : Json( object( m.begin(), m.end() ) ) {}
  106. // Implicit constructor: vector-like objects (std::list, std::vector, std::set, etc)
  107. template <class V, typename std::enable_if<
  108. std::is_constructible<Json, decltype( * std::declval<V>().begin() )>::value,
  109. int>::type = 0>
  110. Json( const V& v ) : Json( array( v.begin(), v.end() ) ) {}
  111. // This prevents Json(some_pointer) from accidentally producing a bool. Use
  112. // Json(bool(some_pointer)) if that behavior is desired.
  113. Json( void* ) = delete;
  114. // Accessors
  115. Type type() const;
  116. bool is_null() const { return type() == NUL; }
  117. bool is_number() const { return type() == NUMBER; }
  118. bool is_bool() const { return type() == BOOL; }
  119. bool is_string() const { return type() == STRING; }
  120. bool is_array() const { return type() == ARRAY; }
  121. bool is_object() const { return type() == OBJECT; }
  122. // Return the enclosed value if this is a number, 0 otherwise. Note that json11 does not
  123. // distinguish between integer and non-integer numbers - number_value() and int_value()
  124. // can both be applied to a NUMBER-typed object.
  125. double number_value() const;
  126. int int_value() const;
  127. // Return the enclosed value if this is a boolean, false otherwise.
  128. bool bool_value() const;
  129. // Return the enclosed string if this is a string, "" otherwise.
  130. const std::string& string_value() const;
  131. // Return the enclosed std::vector if this is an array, or an empty vector otherwise.
  132. const array& array_items() const;
  133. // Return the enclosed std::map if this is an object, or an empty map otherwise.
  134. const object& object_items() const;
  135. // Return a reference to arr[i] if this is an array, Json() otherwise.
  136. const Json& operator[]( size_t i ) const;
  137. // Return a reference to obj[key] if this is an object, Json() otherwise.
  138. const Json& operator[]( const std::string& key ) const;
  139. // Serialize.
  140. void dump( std::string& out ) const;
  141. std::string dump() const
  142. {
  143. std::string out;
  144. dump( out );
  145. return out;
  146. }
  147. // Parse. If parse fails, return Json() and assign an error message to err.
  148. static Json parse( const std::string& in,
  149. std::string& err,
  150. JsonParse strategy = JsonParse::STANDARD );
  151. static Json parse( const char* in,
  152. std::string& err,
  153. JsonParse strategy = JsonParse::STANDARD )
  154. {
  155. if( in )
  156. {
  157. return parse( std::string( in ), err, strategy );
  158. }
  159. else
  160. {
  161. err = "null input";
  162. return nullptr;
  163. }
  164. }
  165. // Parse multiple objects, concatenated or separated by whitespace
  166. static std::vector<Json> parse_multi( const std::string& in,
  167. std::string::size_type& parser_stop_pos,
  168. std::string& err,
  169. JsonParse strategy = JsonParse::STANDARD );
  170. static inline std::vector<Json> parse_multi( const std::string& in,
  171. std::string& err,
  172. JsonParse strategy = JsonParse::STANDARD )
  173. {
  174. std::string::size_type parser_stop_pos;
  175. return parse_multi( in, parser_stop_pos, err, strategy );
  176. }
  177. bool operator==( const Json& rhs ) const;
  178. bool operator<( const Json& rhs ) const;
  179. bool operator!=( const Json& rhs ) const { return !(*this == rhs); }
  180. bool operator<=( const Json& rhs ) const { return !(rhs < *this); }
  181. bool operator>( const Json& rhs ) const { return rhs < *this; }
  182. bool operator>=( const Json& rhs ) const { return !(*this < rhs); }
  183. /* has_shape(types, err)
  184. *
  185. * Return true if this is a JSON object and, for each item in types, has a field of
  186. * the given type. If not, return false and set err to a descriptive message.
  187. */
  188. typedef std::initializer_list<std::pair<std::string, Type> > shape;
  189. bool has_shape( const shape& types, std::string& err ) const;
  190. private:
  191. std::shared_ptr<JsonValue> m_ptr;
  192. };
  193. // Internal class hierarchy - JsonValue objects are not exposed to users of this API.
  194. class JsonValue
  195. {
  196. protected:
  197. friend class Json;
  198. friend class JsonInt;
  199. friend class JsonDouble;
  200. virtual Json::Type type() const = 0;
  201. virtual bool equals( const JsonValue* other ) const = 0;
  202. virtual bool less( const JsonValue* other ) const = 0;
  203. virtual void dump( std::string& out ) const = 0;
  204. virtual double number_value() const;
  205. virtual int int_value() const;
  206. virtual bool bool_value() const;
  207. virtual const std::string& string_value() const;
  208. virtual const Json::array& array_items() const;
  209. virtual const Json& operator[]( size_t i ) const;
  210. virtual const Json::object& object_items() const;
  211. virtual const Json& operator[]( const std::string& key ) const;
  212. virtual ~JsonValue() {}
  213. };
  214. } // namespace json11