• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

open-source-parsers / jsoncpp / 19173639471

07 Nov 2025 03:53PM UTC coverage: 65.346% (-29.9%) from 95.292%
19173639471

push

github

web-flow
Merge bc9f4df9d into ca98c9845

6336 of 12448 branches covered (50.9%)

Branch coverage included in aggregate %.

5838 of 6182 relevant lines covered (94.44%)

10221.46 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

86.11
/include/json/value.h
1
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
2
// Distributed under MIT license, or public domain if desired and
3
// recognized in your jurisdiction.
4
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
5

6
#ifndef JSON_VALUE_H_INCLUDED
7
#define JSON_VALUE_H_INCLUDED
8

9
#if !defined(JSON_IS_AMALGAMATION)
10
#include "forwards.h"
11
#endif // if !defined(JSON_IS_AMALGAMATION)
12

13
// Conditional NORETURN attribute on the throw functions would:
14
// a) suppress false positives from static code analysis
15
// b) possibly improve optimization opportunities.
16
#if !defined(JSONCPP_NORETURN)
17
#if defined(_MSC_VER) && _MSC_VER == 1800
18
#define JSONCPP_NORETURN __declspec(noreturn)
19
#else
20
#define JSONCPP_NORETURN [[noreturn]]
21
#endif
22
#endif
23

24
// Support for '= delete' with template declarations was a late addition
25
// to the c++11 standard and is rejected by clang 3.8 and Apple clang 8.2
26
// even though these declare themselves to be c++11 compilers.
27
#if !defined(JSONCPP_TEMPLATE_DELETE)
28
#if defined(__clang__) && defined(__apple_build_version__)
29
#if __apple_build_version__ <= 8000042
30
#define JSONCPP_TEMPLATE_DELETE
31
#endif
32
#elif defined(__clang__)
33
#if __clang_major__ == 3 && __clang_minor__ <= 8
34
#define JSONCPP_TEMPLATE_DELETE
35
#endif
36
#endif
37
#if !defined(JSONCPP_TEMPLATE_DELETE)
38
#define JSONCPP_TEMPLATE_DELETE = delete
39
#endif
40
#endif
41

42
#if __cplusplus >= 201703L
43
#define JSONCPP_HAS_STRING_VIEW 1
44
#endif
45

46
#include <array>
47
#include <exception>
48
#include <map>
49
#include <memory>
50
#include <string>
51
#include <vector>
52

53
#ifdef JSONCPP_HAS_STRING_VIEW
54
#include <string_view>
55
#endif
56

57
// Disable warning C4251: <data member>: <type> needs to have dll-interface to
58
// be used by...
59
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
60
#pragma warning(push)
61
#pragma warning(disable : 4251 4275)
62
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
63

64
#pragma pack(push)
65
#pragma pack()
66

67
/** \brief JSON (JavaScript Object Notation).
68
 */
69
namespace Json {
70

71
#if JSON_USE_EXCEPTION
72
/** Base class for all exceptions we throw.
73
 *
74
 * We use nothing but these internally. Of course, STL can throw others.
75
 */
76
class JSON_API Exception : public std::exception {
77
public:
78
  Exception(String msg);
79
  ~Exception() noexcept override;
80
  char const* what() const noexcept override;
81

82
protected:
83
  String msg_;
84
};
85

86
/** Exceptions which the user cannot easily avoid.
87
 *
88
 * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
89
 *
90
 * \remark derived from Json::Exception
91
 */
92
class JSON_API RuntimeError : public Exception {
93
public:
94
  RuntimeError(String const& msg);
95
};
96

97
/** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
98
 *
99
 * These are precondition-violations (user bugs) and internal errors (our bugs).
100
 *
101
 * \remark derived from Json::Exception
102
 */
103
class JSON_API LogicError : public Exception {
104
public:
105
  LogicError(String const& msg);
106
};
107
#endif
108

109
/// used internally
110
JSONCPP_NORETURN void throwRuntimeError(String const& msg);
111
/// used internally
112
JSONCPP_NORETURN void throwLogicError(String const& msg);
113

114
/** \brief Type of the value held by a Value object.
115
 */
116
enum ValueType {
117
  nullValue = 0, ///< 'null' value
118
  intValue,      ///< signed integer value
119
  uintValue,     ///< unsigned integer value
120
  realValue,     ///< double value
121
  stringValue,   ///< UTF-8 string value
122
  booleanValue,  ///< bool value
123
  arrayValue,    ///< array value (ordered list)
124
  objectValue    ///< object value (collection of name/value pairs).
125
};
126

127
enum CommentPlacement {
128
  commentBefore = 0,      ///< a comment placed on the line before a value
129
  commentAfterOnSameLine, ///< a comment just after a value on the same line
130
  commentAfter, ///< a comment on the line after a value (only make sense for
131
  /// root value)
132
  numberOfCommentPlacement
133
};
134

135
/** \brief Type of precision for formatting of real values.
136
 */
137
enum PrecisionType {
138
  significantDigits = 0, ///< we set max number of significant digits in string
139
  decimalPlaces          ///< we set max number of digits after "." in string
140
};
141

142
/** \brief Lightweight wrapper to tag static string.
143
 *
144
 * Value constructor and objectValue member assignment takes advantage of the
145
 * StaticString and avoid the cost of string duplication when storing the
146
 * string or the member name.
147
 *
148
 * Example of usage:
149
 * \code
150
 * Json::Value aValue( StaticString("some text") );
151
 * Json::Value object;
152
 * static const StaticString code("code");
153
 * object[code] = 1234;
154
 * \endcode
155
 */
156
class JSON_API StaticString {
157
public:
158
  explicit StaticString(const char* czstring) : c_str_(czstring) {}
159

160
  operator const char*() const { return c_str_; }
161

162
  const char* c_str() const { return c_str_; }
163

164
private:
165
  const char* c_str_;
166
};
167

168
/** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
169
 *
170
 * This class is a discriminated union wrapper that can represents a:
171
 * - signed integer [range: Value::minInt - Value::maxInt]
172
 * - unsigned integer (range: 0 - Value::maxUInt)
173
 * - double
174
 * - UTF-8 string
175
 * - boolean
176
 * - 'null'
177
 * - an ordered list of Value
178
 * - collection of name/value pairs (javascript object)
179
 *
180
 * The type of the held value is represented by a #ValueType and
181
 * can be obtained using type().
182
 *
183
 * Values of an #objectValue or #arrayValue can be accessed using operator[]()
184
 * methods.
185
 * Non-const methods will automatically create the a #nullValue element
186
 * if it does not exist.
187
 * The sequence of an #arrayValue will be automatically resized and initialized
188
 * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
189
 *
190
 * The get() methods can be used to obtain default value in the case the
191
 * required element does not exist.
192
 *
193
 * It is possible to iterate over the list of member keys of an object using
194
 * the getMemberNames() method.
195
 *
196
 * \note #Value string-length fit in size_t, but keys must be < 2^30.
197
 * (The reason is an implementation detail.) A #CharReader will raise an
198
 * exception if a bound is exceeded to avoid security holes in your app,
199
 * but the Value API does *not* check bounds. That is the responsibility
200
 * of the caller.
201
 */
202
class JSON_API Value {
203
  friend class ValueIteratorBase;
204

205
public:
206
  using Members = std::vector<String>;
207
  using iterator = ValueIterator;
208
  using const_iterator = ValueConstIterator;
209
  using UInt = Json::UInt;
210
  using Int = Json::Int;
211
#if defined(JSON_HAS_INT64)
212
  using UInt64 = Json::UInt64;
213
  using Int64 = Json::Int64;
214
#endif // defined(JSON_HAS_INT64)
215
  using LargestInt = Json::LargestInt;
216
  using LargestUInt = Json::LargestUInt;
217
  using ArrayIndex = Json::ArrayIndex;
218

219
  // Required for boost integration, e. g. BOOST_TEST
220
  using value_type = std::string;
221

222
#if JSON_USE_NULLREF
223
  // Binary compatibility kludges, do not use.
224
  static const Value& null;
225
  static const Value& nullRef;
226
#endif
227

228
  // null and nullRef are deprecated, use this instead.
229
  static Value const& nullSingleton();
230

231
  /// Minimum signed integer value that can be stored in a Json::Value.
232
  static constexpr LargestInt minLargestInt =
233
      LargestInt(~(LargestUInt(-1) / 2));
234
  /// Maximum signed integer value that can be stored in a Json::Value.
235
  static constexpr LargestInt maxLargestInt = LargestInt(LargestUInt(-1) / 2);
236
  /// Maximum unsigned integer value that can be stored in a Json::Value.
237
  static constexpr LargestUInt maxLargestUInt = LargestUInt(-1);
238

239
  /// Minimum signed int value that can be stored in a Json::Value.
240
  static constexpr Int minInt = Int(~(UInt(-1) / 2));
241
  /// Maximum signed int value that can be stored in a Json::Value.
242
  static constexpr Int maxInt = Int(UInt(-1) / 2);
243
  /// Maximum unsigned int value that can be stored in a Json::Value.
244
  static constexpr UInt maxUInt = UInt(-1);
245

246
#if defined(JSON_HAS_INT64)
247
  /// Minimum signed 64 bits int value that can be stored in a Json::Value.
248
  static constexpr Int64 minInt64 = Int64(~(UInt64(-1) / 2));
249
  /// Maximum signed 64 bits int value that can be stored in a Json::Value.
250
  static constexpr Int64 maxInt64 = Int64(UInt64(-1) / 2);
251
  /// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
252
  static constexpr UInt64 maxUInt64 = UInt64(-1);
253
#endif // defined(JSON_HAS_INT64)
254
  /// Default precision for real value for string representation.
255
  static constexpr UInt defaultRealPrecision = 17;
256
  // The constant is hard-coded because some compiler have trouble
257
  // converting Value::maxUInt64 to a double correctly (AIX/xlC).
258
  // Assumes that UInt64 is a 64 bits integer.
259
  static constexpr double maxUInt64AsDouble = 18446744073709551615.0;
260
// Workaround for bug in the NVIDIAs CUDA 9.1 nvcc compiler
261
// when using gcc and clang backend compilers.  CZString
262
// cannot be defined as private.  See issue #486
263
#ifdef __NVCC__
264
public:
265
#else
266
private:
267
#endif
268
#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
269
  class CZString {
270
  public:
271
    enum DuplicationPolicy { noDuplication = 0, duplicate, duplicateOnCopy };
272
    CZString(ArrayIndex index);
273
    CZString(char const* str, unsigned length, DuplicationPolicy allocate);
274
    CZString(CZString const& other);
275
    CZString(CZString&& other) noexcept;
276
    ~CZString();
277
    CZString& operator=(const CZString& other);
278
    CZString& operator=(CZString&& other) noexcept;
279

280
    bool operator<(CZString const& other) const;
281
    bool operator==(CZString const& other) const;
282
    ArrayIndex index() const;
283
    // const char* c_str() const; ///< \deprecated
284
    char const* data() const;
285
    unsigned length() const;
286
    bool isStaticString() const;
287

288
  private:
289
    void swap(CZString& other);
290

291
    struct StringStorage {
292
      unsigned policy_ : 2;
293
      unsigned length_ : 30; // 1GB max
294
    };
295

296
    char const* cstr_; // actually, a prefixed string, unless policy is noDup
297
    union {
298
      ArrayIndex index_;
299
      StringStorage storage_;
300
    };
301
  };
302

303
public:
304
  typedef std::map<CZString, Value> ObjectValues;
305
#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
306

307
public:
308
  /**
309
   * \brief Create a default Value of the given type.
310
   *
311
   * This is a very useful constructor.
312
   * To create an empty array, pass arrayValue.
313
   * To create an empty object, pass objectValue.
314
   * Another Value can then be set to this one by assignment.
315
   * This is useful since clear() and resize() will not alter types.
316
   *
317
   * Examples:
318
   *   \code
319
   *   Json::Value null_value; // null
320
   *   Json::Value arr_value(Json::arrayValue); // []
321
   *   Json::Value obj_value(Json::objectValue); // {}
322
   *   \endcode
323
   */
324
  Value(ValueType type = nullValue);
325
  Value(Int value);
326
  Value(UInt value);
327
#if defined(JSON_HAS_INT64)
328
  Value(Int64 value);
329
  Value(UInt64 value);
330
#endif // if defined(JSON_HAS_INT64)
331
  Value(double value);
332
  Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.)
333
  Value(const char* begin, const char* end); ///< Copy all, incl zeroes.
334
  /**
335
   * \brief Constructs a value from a static string.
336
   *
337
   * Like other value string constructor but do not duplicate the string for
338
   * internal storage. The given string must remain alive after the call to
339
   * this constructor.
340
   *
341
   * \note This works only for null-terminated strings. (We cannot change the
342
   * size of this class, so we have nowhere to store the length, which might be
343
   * computed later for various operations.)
344
   *
345
   * Example of usage:
346
   *   \code
347
   *   static StaticString foo("some text");
348
   *   Json::Value aValue(foo);
349
   *   \endcode
350
   */
351
  Value(const StaticString& value);
352
  Value(const String& value);
353
#ifdef JSONCPP_HAS_STRING_VIEW
354
  Value(std::string_view value);
355
#endif
356
  Value(bool value);
357
  Value(std::nullptr_t ptr) = delete;
358
  Value(const Value& other);
359
  Value(Value&& other) noexcept;
360
  ~Value();
361

362
  /// \note Overwrite existing comments. To preserve comments, use
363
  /// #swapPayload().
364
  Value& operator=(const Value& other);
365
  Value& operator=(Value&& other) noexcept;
366

367
  /// Swap everything.
368
  void swap(Value& other);
369
  /// Swap values but leave comments and source offsets in place.
370
  void swapPayload(Value& other);
371

372
  /// copy everything.
373
  void copy(const Value& other);
374
  /// copy values but leave comments and source offsets in place.
375
  void copyPayload(const Value& other);
376

377
  ValueType type() const;
378

379
  /// Compare payload only, not comments etc.
380
  bool operator<(const Value& other) const;
381
  bool operator<=(const Value& other) const;
382
  bool operator>=(const Value& other) const;
383
  bool operator>(const Value& other) const;
384
  bool operator==(const Value& other) const;
385
  bool operator!=(const Value& other) const;
386
  int compare(const Value& other) const;
387

388
  const char* asCString() const; ///< Embedded zeroes could cause you trouble!
389
#if JSONCPP_USE_SECURE_MEMORY
390
  unsigned getCStringLength() const; // Allows you to understand the length of
391
                                     // the CString
392
#endif
393
  String asString() const; ///< Embedded zeroes are possible.
394
  /** Get raw char* of string-value.
395
   *  \return false if !string. (Seg-fault if str or end are NULL.)
396
   */
397
  bool getString(char const** begin, char const** end) const;
398
#ifdef JSONCPP_HAS_STRING_VIEW
399
  /** Get string_view of string-value.
400
   *  \return false if !string. (Seg-fault if str is NULL.)
401
   */
402
  bool getString(std::string_view* str) const;
403
#endif
404
  Int asInt() const;
405
  UInt asUInt() const;
406
#if defined(JSON_HAS_INT64)
407
  Int64 asInt64() const;
408
  UInt64 asUInt64() const;
409
#endif // if defined(JSON_HAS_INT64)
410
  LargestInt asLargestInt() const;
411
  LargestUInt asLargestUInt() const;
412
  float asFloat() const;
413
  double asDouble() const;
414
  bool asBool() const;
415

416
  bool isNull() const;
417
  bool isBool() const;
418
  bool isInt() const;
419
  bool isInt64() const;
420
  bool isUInt() const;
421
  bool isUInt64() const;
422
  bool isIntegral() const;
423
  bool isDouble() const;
424
  bool isNumeric() const;
425
  bool isString() const;
426
  bool isArray() const;
427
  bool isObject() const;
428

429
  /// The `as<T>` and `is<T>` member function templates and specializations.
430
  template <typename T> T as() const JSONCPP_TEMPLATE_DELETE;
431
  template <typename T> bool is() const JSONCPP_TEMPLATE_DELETE;
432

433
  bool isConvertibleTo(ValueType other) const;
434

435
  /// Number of values in array or object
436
  ArrayIndex size() const;
437

438
  /// \brief Return true if empty array, empty object, or null;
439
  /// otherwise, false.
440
  bool empty() const;
441

442
  /// Return !isNull()
443
  explicit operator bool() const;
444

445
  /// Remove all object members and array elements.
446
  /// \pre type() is arrayValue, objectValue, or nullValue
447
  /// \post type() is unchanged
448
  void clear();
449

450
  /// Resize the array to newSize elements.
451
  /// New elements are initialized to null.
452
  /// May only be called on nullValue or arrayValue.
453
  /// \pre type() is arrayValue or nullValue
454
  /// \post type() is arrayValue
455
  void resize(ArrayIndex newSize);
456

457
  ///@{
458
  /// Access an array element (zero based index). If the array contains less
459
  /// than index element, then null value are inserted in the array so that
460
  /// its size is index+1.
461
  /// (You may need to say 'value[0u]' to get your compiler to distinguish
462
  /// this from the operator[] which takes a string.)
463
  Value& operator[](ArrayIndex index);
464
  Value& operator[](int index);
465
  ///@}
466

467
  ///@{
468
  /// Access an array element (zero based index).
469
  /// (You may need to say 'value[0u]' to get your compiler to distinguish
470
  /// this from the operator[] which takes a string.)
471
  const Value& operator[](ArrayIndex index) const;
472
  const Value& operator[](int index) const;
473
  ///@}
474

475
  /// If the array contains at least index+1 elements, returns the element
476
  /// value, otherwise returns defaultValue.
477
  Value get(ArrayIndex index, const Value& defaultValue) const;
478
  /// Return true if index < size().
479
  bool isValidIndex(ArrayIndex index) const;
480
  /// \brief Append value to array at the end.
481
  ///
482
  /// Equivalent to jsonvalue[jsonvalue.size()] = value;
483
  Value& append(const Value& value);
484
  Value& append(Value&& value);
485

486
  /// \brief Insert value in array at specific index
487
  bool insert(ArrayIndex index, const Value& newValue);
488
  bool insert(ArrayIndex index, Value&& newValue);
489

490
#ifdef JSONCPP_HAS_STRING_VIEW
491
  /// Access an object value by name, create a null member if it does not exist.
492
  /// \param key may contain embedded nulls.
493
  Value& operator[](std::string_view key);
494
  /// Access an object value by name, returns null if there is no member with
495
  /// that name.
496
  /// \param key may contain embedded nulls.
497
  const Value& operator[](std::string_view key) const;
498
#else
499
  /// Access an object value by name, create a null member if it does not exist.
500
  /// \note Because of our implementation, keys are limited to 2^30 -1 chars.
501
  /// Exceeding that will cause an exception.
502
  Value& operator[](const char* key);
503
  /// Access an object value by name, returns null if there is no member with
504
  /// that name.
505
  const Value& operator[](const char* key) const;
506
  /// Access an object value by name, create a null member if it does not exist.
507
  /// \param key may contain embedded nulls.
508
  Value& operator[](const String& key);
509
  /// Access an object value by name, returns null if there is no member with
510
  /// that name.
511
  /// \param key may contain embedded nulls.
512
  const Value& operator[](const String& key) const;
513
#endif
514
  /** \brief Access an object value by name, create a null member if it does not
515
   * exist.
516
   *
517
   * If the object has no entry for that name, then the member name used to
518
   * store the new entry is not duplicated.
519
   * Example of use:
520
   *   \code
521
   *   Json::Value object;
522
   *   static const StaticString code("code");
523
   *   object[code] = 1234;
524
   *   \endcode
525
   */
526
  Value& operator[](const StaticString& key);
527
#ifdef JSONCPP_HAS_STRING_VIEW
528
  /// Return the member named key if it exist, defaultValue otherwise.
529
  /// \note deep copy
530
  Value get(std::string_view key, const Value& defaultValue) const;
531
#else
532
  /// Return the member named key if it exist, defaultValue otherwise.
533
  /// \note deep copy
534
  Value get(const char* key, const Value& defaultValue) const;
535
  /// Return the member named key if it exist, defaultValue otherwise.
536
  /// \note deep copy
537
  /// \param key may contain embedded nulls.
538
  Value get(const String& key, const Value& defaultValue) const;
539
#endif
540
  /// Return the member named key if it exist, defaultValue otherwise.
541
  /// \note deep copy
542
  /// \note key may contain embedded nulls.
543
  Value get(const char* begin, const char* end,
544
            const Value& defaultValue) const;
545
  /// Most general and efficient version of isMember()const, get()const,
546
  /// and operator[]const
547
  /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
548
  Value const* find(char const* begin, char const* end) const;
549
  /// Most general and efficient version of isMember()const, get()const,
550
  /// and operator[]const
551
  Value const* find(const String& key) const;
552

553
  /// Calls find and only returns a valid pointer if the type is found
554
  template <typename T, bool (T::*TMemFn)() const>
555
  Value const* findValue(const String& key) const {
×
556
    Value const* found = find(key);
2✔
557
    if (!found || !(found->*TMemFn)())
2!
558
      return nullptr;
2!
559
    return found;
2✔
560
  }
2✔
561

2✔
562
  Value const* findNull(const String& key) const;
2✔
563
  Value const* findBool(const String& key) const;
2✔
564
  Value const* findInt(const String& key) const;
2✔
565
  Value const* findInt64(const String& key) const;
2✔
566
  Value const* findUInt(const String& key) const;
2✔
567
  Value const* findUInt64(const String& key) const;
×
568
  Value const* findIntegral(const String& key) const;
2✔
569
  Value const* findDouble(const String& key) const;
2✔
570
  Value const* findNumeric(const String& key) const;
2✔
571
  Value const* findString(const String& key) const;
2✔
572
  Value const* findArray(const String& key) const;
2✔
573
  Value const* findObject(const String& key) const;
2✔
574

2✔
575
  /// Most general and efficient version of object-mutators.
2✔
576
  /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
2✔
577
  /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
2✔
578
  Value* demand(char const* begin, char const* end);
2✔
579
  /// \brief Remove and return the named member.
×
580
  ///
2✔
581
  /// Do nothing if it did not exist.
2✔
582
  /// \pre type() is objectValue or nullValue
2✔
583
  /// \post type() is unchanged
2✔
584
#if JSONCPP_HAS_STRING_VIEW
2✔
585
  void removeMember(std::string_view key);
2✔
586
#else
2✔
587
  void removeMember(const char* key);
2✔
588
  /// Same as removeMember(const char*)
2✔
589
  /// \param key may contain embedded nulls.
2✔
590
  void removeMember(const String& key);
2✔
591
#endif
×
592
  /** \brief Remove the named map member.
1✔
593
   *
1✔
594
   *  Update 'removed' iff removed.
1✔
595
   *  \param key may contain embedded nulls.
1✔
596
   *  \return true iff removed (no exceptions)
1✔
597
   */
1✔
598
#if JSONCPP_HAS_STRING_VIEW
1✔
599
  bool removeMember(std::string_view key, Value* removed);
1✔
600
#else
1✔
601
  bool removeMember(String const& key, Value* removed);
1✔
602
  /// Same as removeMember(const char* begin, const char* end, Value* removed),
1✔
603
  /// but 'key' is null-terminated.
604
  bool removeMember(const char* key, Value* removed);
605
#endif
606
  /// Same as removeMember(String const& key, Value* removed)
607
  bool removeMember(const char* begin, const char* end, Value* removed);
608
  /** \brief Remove the indexed array element.
609
   *
610
   *  O(n) expensive operations.
611
   *  Update 'removed' iff removed.
612
   *  \return true if removed (no exceptions)
613
   */
614
  bool removeIndex(ArrayIndex index, Value* removed);
615

616
#ifdef JSONCPP_HAS_STRING_VIEW
617
  /// Return true if the object has a member named key.
618
  /// \param key may contain embedded nulls.
619
  bool isMember(std::string_view key) const;
620
#else
621
  /// Return true if the object has a member named key.
622
  /// \note 'key' must be null-terminated.
623
  bool isMember(const char* key) const;
624
  /// Return true if the object has a member named key.
625
  /// \param key may contain embedded nulls.
626
  bool isMember(const String& key) const;
627
#endif
628
  /// Same as isMember(String const& key)const
629
  bool isMember(const char* begin, const char* end) const;
630

631
  /// \brief Return a list of the member names.
632
  ///
633
  /// If null, return an empty list.
634
  /// \pre type() is objectValue or nullValue
635
  /// \post if type() was nullValue, it remains nullValue
636
  Members getMemberNames() const;
637

638
  /// \deprecated Always pass len.
639
  JSONCPP_DEPRECATED("Use setComment(String const&) instead.")
640
  void setComment(const char* comment, CommentPlacement placement) {
641
    setComment(String(comment, strlen(comment)), placement);
642
  }
643
  /// Comments must be //... or /* ... */
644
  void setComment(const char* comment, size_t len, CommentPlacement placement) {
645
    setComment(String(comment, len), placement);
646
  }
647
  /// Comments must be //... or /* ... */
648
  void setComment(String comment, CommentPlacement placement);
649
  bool hasComment(CommentPlacement placement) const;
650
  /// Include delimiters and embedded newlines.
651
  String getComment(CommentPlacement placement) const;
652

653
  String toStyledString() const;
654

655
  const_iterator begin() const;
656
  const_iterator end() const;
657

658
  iterator begin();
659
  iterator end();
660

661
  /// \brief Returns a reference to the first element in the `Value`.
662
  /// Requires that this value holds an array or json object, with at least one
663
  /// element.
664
  const Value& front() const;
665

666
  /// \brief Returns a reference to the first element in the `Value`.
667
  /// Requires that this value holds an array or json object, with at least one
668
  /// element.
669
  Value& front();
670

671
  /// \brief Returns a reference to the last element in the `Value`.
672
  /// Requires that value holds an array or json object, with at least one
673
  /// element.
674
  const Value& back() const;
675

676
  /// \brief Returns a reference to the last element in the `Value`.
677
  /// Requires that this value holds an array or json object, with at least one
678
  /// element.
679
  Value& back();
680

681
  // Accessors for the [start, limit) range of bytes within the JSON text from
682
  // which this value was parsed, if any.
683
  void setOffsetStart(ptrdiff_t start);
684
  void setOffsetLimit(ptrdiff_t limit);
685
  ptrdiff_t getOffsetStart() const;
686
  ptrdiff_t getOffsetLimit() const;
687

688
private:
689
  void setType(ValueType v) {
690
    bits_.value_type_ = static_cast<unsigned char>(v);
691
  }
692
  bool isAllocated() const { return bits_.allocated_; }
693
  void setIsAllocated(bool v) { bits_.allocated_ = v; }
694

695
  void initBasic(ValueType type, bool allocated = false);
696
  void dupPayload(const Value& other);
697
  void releasePayload();
698
  void dupMeta(const Value& other);
699

700
  Value& resolveReference(const char* key);
701
  Value& resolveReference(const char* key, const char* end);
702

703
  // struct MemberNamesTransform
704
  //{
705
  //   typedef const char *result_type;
706
  //   const char *operator()( const CZString &name ) const
707
  //   {
708
  //      return name.c_str();
709
  //   }
710
  //};
711

712
  union ValueHolder {
713
    LargestInt int_;
714
    LargestUInt uint_;
715
    double real_;
716
    bool bool_;
717
    char* string_; // if allocated_, ptr to { unsigned, char[] }.
718
    ObjectValues* map_;
719
  } value_;
720

721
  struct {
722
    // Really a ValueType, but types should agree for bitfield packing.
723
    unsigned int value_type_ : 8;
724
    // Unless allocated_, string_ must be null-terminated.
725
    unsigned int allocated_ : 1;
726
  } bits_;
727

728
  class Comments {
729
  public:
730
    Comments() = default;
731
    Comments(const Comments& that);
732
    Comments(Comments&& that) noexcept;
733
    Comments& operator=(const Comments& that);
734
    Comments& operator=(Comments&& that) noexcept;
735
    bool has(CommentPlacement slot) const;
736
    String get(CommentPlacement slot) const;
737
    void set(CommentPlacement slot, String comment);
738

739
  private:
740
    using Array = std::array<String, numberOfCommentPlacement>;
741
    std::unique_ptr<Array> ptr_;
742
  };
743
  Comments comments_;
744

745
  // [start, limit) byte offsets in the source JSON text from which this Value
746
  // was extracted.
747
  ptrdiff_t start_;
748
  ptrdiff_t limit_;
749
};
750

751
template <> inline bool Value::as<bool>() const { return asBool(); }
752
template <> inline bool Value::is<bool>() const { return isBool(); }
753

754
template <> inline Int Value::as<Int>() const { return asInt(); }
755
template <> inline bool Value::is<Int>() const { return isInt(); }
756

757
template <> inline UInt Value::as<UInt>() const { return asUInt(); }
758
template <> inline bool Value::is<UInt>() const { return isUInt(); }
759

760
#if defined(JSON_HAS_INT64)
761
template <> inline Int64 Value::as<Int64>() const { return asInt64(); }
762
template <> inline bool Value::is<Int64>() const { return isInt64(); }
763

764
template <> inline UInt64 Value::as<UInt64>() const { return asUInt64(); }
765
template <> inline bool Value::is<UInt64>() const { return isUInt64(); }
766
#endif
767

768
template <> inline double Value::as<double>() const { return asDouble(); }
769
template <> inline bool Value::is<double>() const { return isDouble(); }
770

771
template <> inline String Value::as<String>() const { return asString(); }
772
template <> inline bool Value::is<String>() const { return isString(); }
773

774
/// These `as` specializations are type conversions, and do not have a
775
/// corresponding `is`.
776
template <> inline float Value::as<float>() const { return asFloat(); }
777
template <> inline const char* Value::as<const char*>() const {
778
  return asCString();
779
}
780

781
/** \brief Experimental and untested: represents an element of the "path" to
782
 * access a node.
783
 */
784
class JSON_API PathArgument {
785
public:
786
  friend class Path;
787

788
  PathArgument();
789
  PathArgument(ArrayIndex index);
790
  PathArgument(const char* key);
791
  PathArgument(String key);
792

793
private:
794
  enum Kind { kindNone = 0, kindIndex, kindKey };
795
  String key_;
796
  ArrayIndex index_{};
797
  Kind kind_{kindNone};
798
};
799

800
/** \brief Experimental and untested: represents a "path" to access a node.
801
 *
802
 * Syntax:
803
 * - "." => root node
804
 * - ".[n]" => elements at index 'n' of root node (an array value)
805
 * - ".name" => member named 'name' of root node (an object value)
806
 * - ".name1.name2.name3"
807
 * - ".[0][1][2].name1[3]"
808
 * - ".%" => member name is provided as parameter
809
 * - ".[%]" => index is provided as parameter
810
 */
811
class JSON_API Path {
812
public:
813
  Path(const String& path, const PathArgument& a1 = PathArgument(),
814
       const PathArgument& a2 = PathArgument(),
815
       const PathArgument& a3 = PathArgument(),
816
       const PathArgument& a4 = PathArgument(),
817
       const PathArgument& a5 = PathArgument());
818

819
  const Value& resolve(const Value& root) const;
820
  Value resolve(const Value& root, const Value& defaultValue) const;
821
  /// Creates the "path" to access the specified node and returns a reference on
822
  /// the node.
823
  Value& make(Value& root) const;
824

825
private:
826
  using InArgs = std::vector<const PathArgument*>;
827
  using Args = std::vector<PathArgument>;
828

829
  void makePath(const String& path, const InArgs& in);
830
  void addPathInArg(const String& path, const InArgs& in,
831
                    InArgs::const_iterator& itInArg, PathArgument::Kind kind);
832
  static void invalidPath(const String& path, int location);
833

834
  Args args_;
835
};
836

837
/** \brief base class for Value iterators.
838
 *
839
 */
840
class JSON_API ValueIteratorBase {
841
public:
842
  using iterator_category = std::bidirectional_iterator_tag;
843
  using size_t = unsigned int;
844
  using difference_type = int;
845
  using SelfType = ValueIteratorBase;
846

847
  bool operator==(const SelfType& other) const { return isEqual(other); }
848

849
  bool operator!=(const SelfType& other) const { return !isEqual(other); }
850

851
  difference_type operator-(const SelfType& other) const {
852
    return other.computeDistance(*this);
853
  }
854

855
  /// Return either the index or the member name of the referenced value as a
856
  /// Value.
857
  Value key() const;
858

859
  /// Return the index of the referenced Value, or -1 if it is not an
860
  /// arrayValue.
861
  UInt index() const;
862

863
  /// Return the member name of the referenced Value, or "" if it is not an
864
  /// objectValue.
865
  /// \note Avoid `c_str()` on result, as embedded zeroes are possible.
866
  String name() const;
867

868
  /// Return the member name of the referenced Value. "" if it is not an
869
  /// objectValue.
870
  /// \deprecated This cannot be used for UTF-8 strings, since there can be
871
  /// embedded nulls.
872
  JSONCPP_DEPRECATED("Use `key = name();` instead.")
873
  char const* memberName() const;
874
  /// Return the member name of the referenced Value, or NULL if it is not an
875
  /// objectValue.
876
  /// \note Better version than memberName(). Allows embedded nulls.
877
  char const* memberName(char const** end) const;
878

879
protected:
880
  /*! Internal utility functions to assist with implementing
881
   *   other iterator functions. The const and non-const versions
882
   *   of the "deref" protected methods expose the protected
883
   *   current_ member variable in a way that can often be
884
   *   optimized away by the compiler.
885
   */
886
  const Value& deref() const;
887
  Value& deref();
888

889
  void increment();
890

891
  void decrement();
892

893
  difference_type computeDistance(const SelfType& other) const;
894

895
  bool isEqual(const SelfType& other) const;
896

897
  void copy(const SelfType& other);
898

899
private:
900
  Value::ObjectValues::iterator current_;
901
  // Indicates that iterator is for a null value.
902
  bool isNull_{true};
903

904
public:
905
  // For some reason, BORLAND needs these at the end, rather
906
  // than earlier. No idea why.
907
  ValueIteratorBase();
908
  explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
909
};
910

911
/** \brief const iterator for object and array value.
912
 *
913
 */
914
class JSON_API ValueConstIterator : public ValueIteratorBase {
915
  friend class Value;
916

917
public:
918
  using value_type = const Value;
919
  // typedef unsigned int size_t;
920
  // typedef int difference_type;
921
  using reference = const Value&;
922
  using pointer = const Value*;
923
  using SelfType = ValueConstIterator;
924

925
  ValueConstIterator();
926
  ValueConstIterator(ValueIterator const& other);
927

928
private:
929
  /*! \internal Use by Value to create an iterator.
930
   */
931
  explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
932

933
public:
934
  SelfType& operator=(const ValueIteratorBase& other);
935

936
  SelfType operator++(int) {
937
    SelfType temp(*this);
938
    ++*this;
939
    return temp;
940
  }
941

942
  SelfType operator--(int) {
943
    SelfType temp(*this);
944
    --*this;
945
    return temp;
946
  }
947

948
  SelfType& operator--() {
949
    decrement();
950
    return *this;
951
  }
952

953
  SelfType& operator++() {
954
    increment();
955
    return *this;
956
  }
957

958
  reference operator*() const { return deref(); }
959

960
  pointer operator->() const { return &deref(); }
961
};
962

963
/** \brief Iterator for object and array value.
964
 */
965
class JSON_API ValueIterator : public ValueIteratorBase {
966
  friend class Value;
967

968
public:
969
  using value_type = Value;
970
  using size_t = unsigned int;
971
  using difference_type = int;
972
  using reference = Value&;
973
  using pointer = Value*;
974
  using SelfType = ValueIterator;
975

976
  ValueIterator();
977
  explicit ValueIterator(const ValueConstIterator& other);
978
  ValueIterator(const ValueIterator& other);
979

980
private:
981
  /*! \internal Use by Value to create an iterator.
982
   */
983
  explicit ValueIterator(const Value::ObjectValues::iterator& current);
984

985
public:
986
  SelfType& operator=(const SelfType& other);
987

988
  SelfType operator++(int) {
989
    SelfType temp(*this);
990
    ++*this;
991
    return temp;
992
  }
993

994
  SelfType operator--(int) {
995
    SelfType temp(*this);
996
    --*this;
997
    return temp;
998
  }
999

1000
  SelfType& operator--() {
1001
    decrement();
1002
    return *this;
1003
  }
1004

1005
  SelfType& operator++() {
1006
    increment();
1007
    return *this;
1008
  }
1009

1010
  /*! The return value of non-const iterators can be
1011
   *  changed, so the these functions are not const
1012
   *  because the returned references/pointers can be used
1013
   *  to change state of the base class.
1014
   */
1015
  reference operator*() const { return const_cast<reference>(deref()); }
1016
  pointer operator->() const { return const_cast<pointer>(&deref()); }
1017
};
1018

1019
inline void swap(Value& a, Value& b) { a.swap(b); }
1020

1021
inline const Value& Value::front() const { return *begin(); }
1022

1023
inline Value& Value::front() { return *begin(); }
1024

1025
inline const Value& Value::back() const { return *(--end()); }
1✔
1026

1027
inline Value& Value::back() { return *(--end()); }
6✔
1028

1029
} // namespace Json
1030

1031
#pragma pack(pop)
1032

1033
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1034
#pragma warning(pop)
1035
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1036

1037
#endif // JSON_H_INCLUDED
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc