OPAL
json11.hpp
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 
30 /* Copyright (c) 2013 Dropbox, Inc.
31  *
32  * Permission is hereby granted, free of charge, to any person obtaining a copy
33  * of this software and associated documentation files (the "Software"), to deal
34  * in the Software without restriction, including without limitation the rights
35  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
36  * copies of the Software, and to permit persons to whom the Software is
37  * furnished to do so, subject to the following conditions:
38  *
39  * The above copyright notice and this permission notice shall be included in
40  * all copies or substantial portions of the Software.
41  *
42  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
43  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
44  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
45  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
46  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
47  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
48  * THE SOFTWARE.
49  */
50 
51 #pragma once
52 
53 #include <string>
54 #include <vector>
55 #include <map>
56 #include <memory>
57 #include <initializer_list>
58 
59 #ifdef _MSC_VER
60  #if _MSC_VER <= 1800 // VS 2013
61  #ifndef noexcept
62  #define noexcept throw()
63  #endif
64 
65  #ifndef snprintf
66  #define snprintf _snprintf_s
67  #endif
68  #endif
69 #endif
70 
71 namespace json11 {
72 
73 enum JsonParse {
74  STANDARD, COMMENTS
75 };
76 
77 class JsonValue;
78 
79 class Json final {
80 public:
81  // Types
82  enum Type {
83  NUL, NUMBER, BOOL, STRING, ARRAY, OBJECT
84  };
85 
86  // Array and object typedefs
87  typedef std::vector<Json> array;
88  typedef std::map<std::string, Json> object;
89 
90  // Constructors for the various types of JSON value.
91  Json() noexcept; // NUL
92  Json(std::nullptr_t) noexcept; // NUL
93  Json(double value); // NUMBER
94  Json(int value); // NUMBER
95  Json(bool value); // BOOL
96  Json(const std::string &value); // STRING
97  Json(std::string &&value); // STRING
98  Json(const char * value); // STRING
99  Json(const array &values); // ARRAY
100  Json(array &&values); // ARRAY
101  Json(const object &values); // OBJECT
102  Json(object &&values); // OBJECT
103 
104  // Implicit constructor: anything with a to_json() function.
105  template <class T, class = decltype(&T::to_json)>
106  Json(const T & t) : Json(t.to_json()) {}
107 
108  // Implicit constructor: map-like objects (std::map, std::unordered_map, etc)
109  template <class M, typename std::enable_if<
110  std::is_constructible<std::string, typename M::key_type>::value
111  && std::is_constructible<Json, typename M::mapped_type>::value,
112  int>::type = 0>
113  Json(const M & m) : Json(object(m.begin(), m.end())) {}
114 
115  // Implicit constructor: vector-like objects (std::list, std::vector, std::set, etc)
116  template <class V, typename std::enable_if<
117  std::is_constructible<Json, typename V::value_type>::value,
118  int>::type = 0>
119  Json(const V & v) : Json(array(v.begin(), v.end())) {}
120 
121  // This prevents Json(some_pointer) from accidentally producing a bool. Use
122  // Json(bool(some_pointer)) if that behavior is desired.
123  Json(void *) = delete;
124 
125  // Accessors
126  Type type() const;
127 
128  bool is_null() const { return type() == NUL; }
129  bool is_number() const { return type() == NUMBER; }
130  bool is_bool() const { return type() == BOOL; }
131  bool is_string() const { return type() == STRING; }
132  bool is_array() const { return type() == ARRAY; }
133  bool is_object() const { return type() == OBJECT; }
134 
135  // Return the enclosed value if this is a number, 0 otherwise. Note that json11 does not
136  // distinguish between integer and non-integer numbers - number_value() and int_value()
137  // can both be applied to a NUMBER-typed object.
138  double number_value() const;
139  int int_value() const;
140 
141  // Return the enclosed value if this is a boolean, false otherwise.
142  bool bool_value() const;
143  // Return the enclosed string if this is a string, "" otherwise.
144  const std::string &string_value() const;
145  // Return the enclosed std::vector if this is an array, or an empty vector otherwise.
146  const array &array_items() const;
147  // Return the enclosed std::map if this is an object, or an empty map otherwise.
148  const object &object_items() const;
149 
150  // Return a reference to arr[i] if this is an array, Json() otherwise.
151  const Json & operator[](size_t i) const;
152  // Return a reference to obj[key] if this is an object, Json() otherwise.
153  const Json & operator[](const std::string &key) const;
154 
155  // Serialize.
156  void dump(std::string &out) const;
157  std::string dump() const {
158  std::string out;
159  dump(out);
160  return out;
161  }
162 
163  // Parse. If parse fails, return Json() and assign an error message to err.
164  static Json parse(const std::string & in,
165  std::string & err,
166  JsonParse strategy = JsonParse::STANDARD);
167  static Json parse(const char * in,
168  std::string & err,
169  JsonParse strategy = JsonParse::STANDARD) {
170  if (in) {
171  return parse(std::string(in), err, strategy);
172  } else {
173  err = "null input";
174  return nullptr;
175  }
176  }
177  // Parse multiple objects, concatenated or separated by whitespace
178  static std::vector<Json> parse_multi(
179  const std::string & in,
180  std::string::size_type & parser_stop_pos,
181  std::string & err,
182  JsonParse strategy = JsonParse::STANDARD);
183 
184  static inline std::vector<Json> parse_multi(
185  const std::string & in,
186  std::string & err,
187  JsonParse strategy = JsonParse::STANDARD) {
188  std::string::size_type parser_stop_pos;
189  return parse_multi(in, parser_stop_pos, err, strategy);
190  }
191 
192  bool operator== (const Json &rhs) const;
193  bool operator< (const Json &rhs) const;
194  bool operator!= (const Json &rhs) const { return !(*this == rhs); }
195  bool operator<= (const Json &rhs) const { return !(rhs < *this); }
196  bool operator> (const Json &rhs) const { return (rhs < *this); }
197  bool operator>= (const Json &rhs) const { return !(*this < rhs); }
198 
199  /* has_shape(types, err)
200  *
201  * Return true if this is a JSON object and, for each item in types, has a field of
202  * the given type. If not, return false and set err to a descriptive message.
203  */
204  typedef std::initializer_list<std::pair<std::string, Type>> shape;
205  bool has_shape(const shape & types, std::string & err) const;
206 
207 private:
208  std::shared_ptr<JsonValue> m_ptr;
209 };
210 
211 // Internal class hierarchy - JsonValue objects are not exposed to users of this API.
212 class JsonValue {
213 protected:
214  friend class Json;
215  friend class JsonInt;
216  friend class JsonDouble;
217  virtual Json::Type type() const = 0;
218  virtual bool equals(const JsonValue * other) const = 0;
219  virtual bool less(const JsonValue * other) const = 0;
220  virtual void dump(std::string &out) const = 0;
221  virtual double number_value() const;
222  virtual int int_value() const;
223  virtual bool bool_value() const;
224  virtual const std::string &string_value() const;
225  virtual const Json::array &array_items() const;
226  virtual const Json &operator[](size_t i) const;
227  virtual const Json::object &object_items() const;
228  virtual const Json &operator[](const std::string &key) const;
229  virtual ~JsonValue() {}
230 };
231 
232 } // namespace json11
Definition: json11.cpp:173
Definition: json11.hpp:79
Definition: json11.hpp:212
Definition: json11.cpp:29
Definition: json11.cpp:182