1 /// Json-cpp amalgated header (http://jsoncpp.sourceforge.net/).
2 /// It is intended to be used with #include "json/json.h"
4 // //////////////////////////////////////////////////////////////////////
5 // Beginning of content of file: LICENSE
6 // //////////////////////////////////////////////////////////////////////
9 The JsonCpp library's source code, including accompanying documentation,
10 tests and demonstration applications, are licensed under the following
13 The author (Baptiste Lepilleur) explicitly disclaims copyright in all
14 jurisdictions which recognize such a disclaimer. In such jurisdictions,
15 this software is released into the Public Domain.
17 In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
18 2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
19 released under the terms of the MIT License (see below).
21 In jurisdictions which recognize Public Domain property, the user of this
22 software may choose to accept it either as 1) Public Domain, 2) under the
23 conditions of the MIT License (see below), or 3) under the terms of dual
24 Public Domain/MIT License conditions described here, as they choose.
26 The MIT License is about as close to Public Domain as a license can get, and is
27 described in clear, concise terms at:
29 http://en.wikipedia.org/wiki/MIT_License
31 The full text of the MIT License follows:
33 ========================================================================
34 Copyright (c) 2007-2010 Baptiste Lepilleur
36 Permission is hereby granted, free of charge, to any person
37 obtaining a copy of this software and associated documentation
38 files (the "Software"), to deal in the Software without
39 restriction, including without limitation the rights to use, copy,
40 modify, merge, publish, distribute, sublicense, and/or sell copies
41 of the Software, and to permit persons to whom the Software is
42 furnished to do so, subject to the following conditions:
44 The above copyright notice and this permission notice shall be
45 included in all copies or substantial portions of the Software.
47 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
48 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
49 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
50 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
51 BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
52 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
53 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
55 ========================================================================
58 The MIT license is compatible with both the GPL and commercial
59 software, affording one all of the rights of Public Domain with the
60 minor nuisance of being required to keep the above copyright notice
61 and license text in the source code. Note also that by accepting the
62 Public Domain "license" you can re-license your copy using whatever
67 // //////////////////////////////////////////////////////////////////////
68 // End of content of file: LICENSE
69 // //////////////////////////////////////////////////////////////////////
71 #ifndef JSON_AMALGATED_H_INCLUDED
72 #define JSON_AMALGATED_H_INCLUDED
73 /// If defined, indicates that the source file is amalgated
74 /// to prevent private header inclusion.
75 #define JSON_IS_AMALGAMATION
77 // //////////////////////////////////////////////////////////////////////
78 // Beginning of content of file: include/json/version.h
79 // //////////////////////////////////////////////////////////////////////
81 // DO NOT EDIT. This file (and "version") is generated by CMake.
82 // Run CMake configure step to update it.
83 #ifndef JSON_VERSION_H_INCLUDED
84 #define JSON_VERSION_H_INCLUDED
86 #define JSONCPP_VERSION_STRING "1.7.7"
87 #define JSONCPP_VERSION_MAJOR 1
88 #define JSONCPP_VERSION_MINOR 7
89 #define JSONCPP_VERSION_PATCH 7
90 #define JSONCPP_VERSION_QUALIFIER
91 #define JSONCPP_VERSION_HEXA \
92 ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8))
94 #ifdef JSONCPP_USING_SECURE_MEMORY
95 #undef JSONCPP_USING_SECURE_MEMORY
97 #define JSONCPP_USING_SECURE_MEMORY 0
98 // If non-zero, the library zeroes any memory that it has allocated before
99 // it frees its memory.
101 #endif // JSON_VERSION_H_INCLUDED
103 // //////////////////////////////////////////////////////////////////////
104 // End of content of file: include/json/version.h
105 // //////////////////////////////////////////////////////////////////////
107 // //////////////////////////////////////////////////////////////////////
108 // Beginning of content of file: include/json/config.h
109 // //////////////////////////////////////////////////////////////////////
111 // Copyright 2007-2010 Baptiste Lepilleur
112 // Distributed under MIT license, or public domain if desired and
113 // recognized in your jurisdiction.
114 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
116 #ifndef JSON_CONFIG_H_INCLUDED
117 #define JSON_CONFIG_H_INCLUDED
119 #include <string> //typedef String
120 #include <stdint.h> //typedef int64_t, uint64_t
122 /// If defined, indicates that json library is embedded in CppTL library.
123 //# define JSON_IN_CPPTL 1
125 /// If defined, indicates that json may leverage CppTL library
126 //# define JSON_USE_CPPTL 1
127 /// If defined, indicates that cpptl vector based map should be used instead of
129 /// as Value container.
130 //# define JSON_USE_CPPTL_SMALLMAP 1
132 // If non-zero, the library uses exceptions to report bad input instead of C
133 // assertion macros. The default is to use exceptions.
134 #ifndef JSON_USE_EXCEPTION
135 #define JSON_USE_EXCEPTION 1
138 /// If defined, indicates that the source file is amalgated
139 /// to prevent private header inclusion.
140 /// Remarks: it is automatically defined in the generated amalgated header.
141 // #define JSON_IS_AMALGAMATION
144 #include <cpptl/config.h>
145 #ifndef JSON_USE_CPPTL
146 #define JSON_USE_CPPTL 1
151 #define JSON_API CPPTL_API
152 #elif defined(JSON_DLL_BUILD)
153 #if defined(_MSC_VER) || defined(__MINGW32__)
154 #define JSON_API __declspec(dllexport)
155 #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
156 #endif // if defined(_MSC_VER)
157 #elif defined(JSON_DLL)
158 #if defined(_MSC_VER) || defined(__MINGW32__)
159 #define JSON_API __declspec(dllimport)
160 #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
161 #endif // if defined(_MSC_VER)
162 #endif // ifdef JSON_IN_CPPTL
163 #if !defined(JSON_API)
167 // If JSON_NO_INT64 is defined, then Json only support C++ "int" type for
169 // Storages, and 64 bits integer support is disabled.
170 // #define JSON_NO_INT64 1
172 #if defined(_MSC_VER) // MSVC
173 #if _MSC_VER <= 1200 // MSVC 6
174 // Microsoft Visual Studio 6 only support conversion from __int64 to double
175 // (no conversion from unsigned __int64).
176 #define JSON_USE_INT64_DOUBLE_CONVERSION 1
177 // Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255'
178 // characters in the debug information)
179 // All projects I've ever seen with VS6 were using this globally (not bothering
180 // with pragma push/pop).
181 #pragma warning(disable : 4786)
184 #if _MSC_VER >= 1500 // MSVC 2008
185 /// Indicates that the following function is deprecated.
186 #define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
189 #endif // defined(_MSC_VER)
191 // In c++11 the override keyword allows you to explicity define that a function
192 // is intended to override the base-class version. This makes the code more
193 // managable and fixes a set of common hard-to-find bugs.
194 #if __cplusplus >= 201103L
195 #define JSONCPP_OVERRIDE override
196 #elif defined(_MSC_VER) && _MSC_VER > 1600
197 #define JSONCPP_OVERRIDE override
199 #define JSONCPP_OVERRIDE
202 #ifndef JSON_HAS_RVALUE_REFERENCES
204 #if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010
205 #define JSON_HAS_RVALUE_REFERENCES 1
206 #endif // MSVC >= 2010
209 #if __has_feature(cxx_rvalue_references)
210 #define JSON_HAS_RVALUE_REFERENCES 1
211 #endif // has_feature
213 #elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
214 #if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L)
215 #define JSON_HAS_RVALUE_REFERENCES 1
216 #endif // GXX_EXPERIMENTAL
218 #endif // __clang__ || __GNUC__
220 #endif // not defined JSON_HAS_RVALUE_REFERENCES
222 #ifndef JSON_HAS_RVALUE_REFERENCES
223 #define JSON_HAS_RVALUE_REFERENCES 0
227 #elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
228 #if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
229 #define JSONCPP_DEPRECATED(message) __attribute__((deprecated(message)))
230 #elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
231 #define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__))
232 #endif // GNUC version
233 #endif // __clang__ || __GNUC__
235 #if !defined(JSONCPP_DEPRECATED)
236 #define JSONCPP_DEPRECATED(message)
237 #endif // if !defined(JSONCPP_DEPRECATED)
240 #define JSON_USE_INT64_DOUBLE_CONVERSION 1
243 #if !defined(JSON_IS_AMALGAMATION)
247 #if JSONCPP_USING_SECURE_MEMORY
248 #include "allocator.h" //typedef Allocator
251 #endif // if !defined(JSON_IS_AMALGAMATION)
256 typedef unsigned int UInt;
257 #if defined(JSON_NO_INT64)
258 typedef int LargestInt;
259 typedef unsigned int LargestUInt;
260 #undef JSON_HAS_INT64
261 #else // if defined(JSON_NO_INT64)
262 // For Microsoft Visual use specific types as long long is not supported
263 #if defined(_MSC_VER) // Microsoft Visual Studio
264 typedef __int64 Int64;
265 typedef unsigned __int64 UInt64;
266 #else // if defined(_MSC_VER) // Other platforms, use long long
267 typedef int64_t Int64;
268 typedef uint64_t UInt64;
269 #endif // if defined(_MSC_VER)
270 typedef Int64 LargestInt;
271 typedef UInt64 LargestUInt;
272 #define JSON_HAS_INT64
273 #endif // if defined(JSON_NO_INT64)
274 #if JSONCPP_USING_SECURE_MEMORY
275 #define JSONCPP_STRING std::basic_string<char, std::char_traits<char>, Json::SecureAllocator<char>>
276 #define JSONCPP_OSTRINGSTREAM \
277 std::basic_ostringstream<char, std::char_traits<char>, Json::SecureAllocator<char>>
278 #define JSONCPP_OSTREAM std::basic_ostream<char, std::char_traits<char>>
279 #define JSONCPP_ISTRINGSTREAM \
280 std::basic_istringstream<char, std::char_traits<char>, Json::SecureAllocator<char>>
281 #define JSONCPP_ISTREAM std::istream
283 #define JSONCPP_STRING std::string
284 #define JSONCPP_OSTRINGSTREAM std::ostringstream
285 #define JSONCPP_OSTREAM std::ostream
286 #define JSONCPP_ISTRINGSTREAM std::istringstream
287 #define JSONCPP_ISTREAM std::istream
288 #endif // if JSONCPP_USING_SECURE_MEMORY
289 } // end namespace Json
291 #endif // JSON_CONFIG_H_INCLUDED
293 // //////////////////////////////////////////////////////////////////////
294 // End of content of file: include/json/config.h
295 // //////////////////////////////////////////////////////////////////////
297 // //////////////////////////////////////////////////////////////////////
298 // Beginning of content of file: include/json/forwards.h
299 // //////////////////////////////////////////////////////////////////////
301 // Copyright 2007-2010 Baptiste Lepilleur
302 // Distributed under MIT license, or public domain if desired and
303 // recognized in your jurisdiction.
304 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
306 #ifndef JSON_FORWARDS_H_INCLUDED
307 #define JSON_FORWARDS_H_INCLUDED
309 #if !defined(JSON_IS_AMALGAMATION)
311 #endif // if !defined(JSON_IS_AMALGAMATION)
327 typedef unsigned int ArrayIndex;
332 class ValueIteratorBase;
334 class ValueConstIterator;
338 #endif // JSON_FORWARDS_H_INCLUDED
340 // //////////////////////////////////////////////////////////////////////
341 // End of content of file: include/json/forwards.h
342 // //////////////////////////////////////////////////////////////////////
344 // //////////////////////////////////////////////////////////////////////
345 // Beginning of content of file: include/json/features.h
346 // //////////////////////////////////////////////////////////////////////
348 // Copyright 2007-2010 Baptiste Lepilleur
349 // Distributed under MIT license, or public domain if desired and
350 // recognized in your jurisdiction.
351 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
353 #ifndef CPPTL_JSON_FEATURES_H_INCLUDED
354 #define CPPTL_JSON_FEATURES_H_INCLUDED
356 #if !defined(JSON_IS_AMALGAMATION)
357 #include "forwards.h"
358 #endif // if !defined(JSON_IS_AMALGAMATION)
363 /** \brief Configuration passed to reader and writer.
364 * This configuration object can be used to force the Reader or Writer
365 * to behave in a standard conforming way.
367 class JSON_API Features
370 /** \brief A configuration that allows all features and assumes all strings
372 * - C & C++ comments are allowed
373 * - Root object can be any JSON value
374 * - Assumes Value strings are encoded in UTF-8
376 static Features all();
378 /** \brief A configuration that is strictly compatible with the JSON
380 * - Comments are forbidden.
381 * - Root object must be either an array or an object value.
382 * - Assumes Value strings are encoded in UTF-8
384 static Features strictMode();
386 /** \brief Initialize the configuration like JsonConfig::allFeatures;
390 /// \c true if comments are allowed. Default: \c true.
393 /// \c true if root must be either an array or an object value. Default: \c
397 /// \c true if dropped null placeholders are allowed. Default: \c false.
398 bool allowDroppedNullPlaceholders_;
400 /// \c true if numeric object key are allowed. Default: \c false.
401 bool allowNumericKeys_;
406 #endif // CPPTL_JSON_FEATURES_H_INCLUDED
408 // //////////////////////////////////////////////////////////////////////
409 // End of content of file: include/json/features.h
410 // //////////////////////////////////////////////////////////////////////
412 // //////////////////////////////////////////////////////////////////////
413 // Beginning of content of file: include/json/value.h
414 // //////////////////////////////////////////////////////////////////////
416 // Copyright 2007-2010 Baptiste Lepilleur
417 // Distributed under MIT license, or public domain if desired and
418 // recognized in your jurisdiction.
419 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
421 #ifndef CPPTL_JSON_H_INCLUDED
422 #define CPPTL_JSON_H_INCLUDED
424 #if !defined(JSON_IS_AMALGAMATION)
425 #include "forwards.h"
426 #endif // if !defined(JSON_IS_AMALGAMATION)
431 #ifndef JSON_USE_CPPTL_SMALLMAP
434 #include <cpptl/smallmap.h>
436 #ifdef JSON_USE_CPPTL
437 #include <cpptl/forwards.h>
440 // Conditional NORETURN attribute on the throw functions would:
441 // a) suppress false positives from static code analysis
442 // b) possibly improve optimization opportunities.
443 #if !defined(JSONCPP_NORETURN)
444 #if defined(_MSC_VER)
445 #define JSONCPP_NORETURN __declspec(noreturn)
446 #elif defined(__GNUC__)
447 #define JSONCPP_NORETURN __attribute__((__noreturn__))
449 #define JSONCPP_NORETURN
453 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
455 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
456 #pragma warning(push)
457 #pragma warning(disable : 4251)
458 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
460 /** \brief JSON (JavaScript Object Notation).
465 /** Base class for all exceptions we throw.
467 * We use nothing but these internally. Of course, STL can throw others.
469 class JSON_API Exception : public std::exception
472 Exception(JSONCPP_STRING const &msg);
473 ~Exception() throw() JSONCPP_OVERRIDE;
474 char const *what() const throw() JSONCPP_OVERRIDE;
480 /** Exceptions which the user cannot easily avoid.
482 * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
484 * \remark derived from Json::Exception
486 class JSON_API RuntimeError : public Exception
489 RuntimeError(JSONCPP_STRING const &msg);
492 /** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
494 * These are precondition-violations (user bugs) and internal errors (our bugs).
496 * \remark derived from Json::Exception
498 class JSON_API LogicError : public Exception
501 LogicError(JSONCPP_STRING const &msg);
505 JSONCPP_NORETURN void throwRuntimeError(JSONCPP_STRING const &msg);
507 JSONCPP_NORETURN void throwLogicError(JSONCPP_STRING const &msg);
509 /** \brief Type of the value held by a Value object.
513 nullValue = 0, ///< 'null' value
514 intValue, ///< signed integer value
515 uintValue, ///< unsigned integer value
516 realValue, ///< double value
517 stringValue, ///< UTF-8 string value
518 booleanValue, ///< bool value
519 arrayValue, ///< array value (ordered list)
520 objectValue ///< object value (collection of name/value pairs).
523 enum CommentPlacement
525 commentBefore = 0, ///< a comment placed on the line before a value
526 commentAfterOnSameLine, ///< a comment just after a value on the same line
527 commentAfter, ///< a comment on the line after a value (only make sense for
529 numberOfCommentPlacement
532 //# ifdef JSON_USE_CPPTL
533 // typedef CppTL::AnyEnumerator<const char *> EnumMemberNames;
534 // typedef CppTL::AnyEnumerator<const Value &> EnumValues;
537 /** \brief Lightweight wrapper to tag static string.
539 * Value constructor and objectValue member assignement takes advantage of the
540 * StaticString and avoid the cost of string duplication when storing the
541 * string or the member name.
545 * Json::Value aValue( StaticString("some text") );
546 * Json::Value object;
547 * static const StaticString code("code");
548 * object[code] = 1234;
551 class JSON_API StaticString
554 explicit StaticString(const char *czstring) : c_str_(czstring) {}
556 operator const char *() const { return c_str_; }
558 const char *c_str() const { return c_str_; }
564 /** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
566 * This class is a discriminated union wrapper that can represents a:
567 * - signed integer [range: Value::minInt - Value::maxInt]
568 * - unsigned integer (range: 0 - Value::maxUInt)
573 * - an ordered list of Value
574 * - collection of name/value pairs (javascript object)
576 * The type of the held value is represented by a #ValueType and
577 * can be obtained using type().
579 * Values of an #objectValue or #arrayValue can be accessed using operator[]()
581 * Non-const methods will automatically create the a #nullValue element
582 * if it does not exist.
583 * The sequence of an #arrayValue will be automatically resized and initialized
584 * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
586 * The get() methods can be used to obtain default value in the case the
587 * required element does not exist.
589 * It is possible to iterate over the list of a #objectValue values using
590 * the getMemberNames() method.
592 * \note #Value string-length fit in size_t, but keys must be < 2^30.
593 * (The reason is an implementation detail.) A #CharReader will raise an
594 * exception if a bound is exceeded to avoid security holes in your app,
595 * but the Value API does *not* check bounds. That is the responsibility
600 friend class ValueIteratorBase;
603 typedef std::vector<JSONCPP_STRING> Members;
604 typedef ValueIterator iterator;
605 typedef ValueConstIterator const_iterator;
606 typedef Json::UInt UInt;
607 typedef Json::Int Int;
608 #if defined(JSON_HAS_INT64)
609 typedef Json::UInt64 UInt64;
610 typedef Json::Int64 Int64;
611 #endif // defined(JSON_HAS_INT64)
612 typedef Json::LargestInt LargestInt;
613 typedef Json::LargestUInt LargestUInt;
614 typedef Json::ArrayIndex ArrayIndex;
617 &null; ///< We regret this reference to a global instance; prefer the simpler Value().
618 static const Value &nullRef; ///< just a kludge for binary-compatibility; same as null
619 static Value const &nullSingleton(); ///< Prefer this to null or nullRef.
621 /// Minimum signed integer value that can be stored in a Json::Value.
622 static const LargestInt minLargestInt;
623 /// Maximum signed integer value that can be stored in a Json::Value.
624 static const LargestInt maxLargestInt;
625 /// Maximum unsigned integer value that can be stored in a Json::Value.
626 static const LargestUInt maxLargestUInt;
628 /// Minimum signed int value that can be stored in a Json::Value.
629 static const Int minInt;
630 /// Maximum signed int value that can be stored in a Json::Value.
631 static const Int maxInt;
632 /// Maximum unsigned int value that can be stored in a Json::Value.
633 static const UInt maxUInt;
635 #if defined(JSON_HAS_INT64)
636 /// Minimum signed 64 bits int value that can be stored in a Json::Value.
637 static const Int64 minInt64;
638 /// Maximum signed 64 bits int value that can be stored in a Json::Value.
639 static const Int64 maxInt64;
640 /// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
641 static const UInt64 maxUInt64;
642 #endif // defined(JSON_HAS_INT64)
645 #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
649 enum DuplicationPolicy
655 CZString(ArrayIndex index);
656 CZString(char const *str, unsigned length, DuplicationPolicy allocate);
657 CZString(CZString const &other);
658 #if JSON_HAS_RVALUE_REFERENCES
659 CZString(CZString &&other);
662 CZString &operator=(CZString other);
663 bool operator<(CZString const &other) const;
664 bool operator==(CZString const &other) const;
665 ArrayIndex index() const;
666 // const char* c_str() const; ///< \deprecated
667 char const *data() const;
668 unsigned length() const;
669 bool isStaticString() const;
672 void swap(CZString &other);
676 unsigned policy_ : 2;
677 unsigned length_ : 30; // 1GB max
680 char const *cstr_; // actually, a prefixed string, unless policy is noDup
683 StringStorage storage_;
688 #ifndef JSON_USE_CPPTL_SMALLMAP
689 typedef std::map<CZString, Value> ObjectValues;
691 typedef CppTL::SmallMap<CZString, Value> ObjectValues;
692 #endif // ifndef JSON_USE_CPPTL_SMALLMAP
693 #endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
696 /** \brief Create a default Value of the given type.
698 This is a very useful constructor.
699 To create an empty array, pass arrayValue.
700 To create an empty object, pass objectValue.
701 Another Value can then be set to this one by assignment.
702 This is useful since clear() and resize() will not alter types.
706 Json::Value null_value; // null
707 Json::Value arr_value(Json::arrayValue); // []
708 Json::Value obj_value(Json::objectValue); // {}
711 Value(ValueType type = nullValue);
714 #if defined(JSON_HAS_INT64)
717 #endif // if defined(JSON_HAS_INT64)
719 Value(const char *value); ///< Copy til first 0. (NULL causes to seg-fault.)
720 Value(const char *begin, const char *end); ///< Copy all, incl zeroes.
721 /** \brief Constructs a value from a static string.
723 * Like other value string constructor but do not duplicate the string for
724 * internal storage. The given string must remain alive after the call to this
726 * \note This works only for null-terminated strings. (We cannot change the
727 * size of this class, so we have nowhere to store the length,
728 * which might be computed later for various operations.)
732 * static StaticString foo("some text");
733 * Json::Value aValue(foo);
736 Value(const StaticString &value);
737 Value(const JSONCPP_STRING &value); ///< Copy data() til size(). Embedded zeroes too.
738 #ifdef JSON_USE_CPPTL
739 Value(const CppTL::ConstString &value);
743 Value(const Value &other);
744 #if JSON_HAS_RVALUE_REFERENCES
746 Value(Value &&other);
750 /// Deep copy, then swap(other).
751 /// \note Over-write existing comments. To preserve comments, use #swapPayload().
752 Value &operator=(Value other);
754 void swap(Value &other);
755 /// Swap values but leave comments and source offsets in place.
756 void swapPayload(Value &other);
758 ValueType type() const;
760 /// Compare payload only, not comments etc.
761 bool operator<(const Value &other) const;
762 bool operator<=(const Value &other) const;
763 bool operator>=(const Value &other) const;
764 bool operator>(const Value &other) const;
765 bool operator==(const Value &other) const;
766 bool operator!=(const Value &other) const;
767 int compare(const Value &other) const;
769 const char *asCString() const; ///< Embedded zeroes could cause you trouble!
770 #if JSONCPP_USING_SECURE_MEMORY
771 unsigned getCStringLength() const; // Allows you to understand the length of the CString
773 JSONCPP_STRING asString() const; ///< Embedded zeroes are possible.
774 /** Get raw char* of string-value.
775 * \return false if !string. (Seg-fault if str or end are NULL.)
777 bool getString(char const **begin, char const **end) const;
778 #ifdef JSON_USE_CPPTL
779 CppTL::ConstString asConstString() const;
783 #if defined(JSON_HAS_INT64)
784 Int64 asInt64() const;
785 UInt64 asUInt64() const;
786 #endif // if defined(JSON_HAS_INT64)
787 LargestInt asLargestInt() const;
788 LargestUInt asLargestUInt() const;
789 float asFloat() const;
790 double asDouble() const;
796 bool isInt64() const;
798 bool isUInt64() const;
799 bool isIntegral() const;
800 bool isDouble() const;
801 bool isNumeric() const;
802 bool isString() const;
803 bool isArray() const;
804 bool isObject() const;
806 bool isConvertibleTo(ValueType other) const;
808 /// Number of values in array or object
809 ArrayIndex size() const;
811 /// \brief Return true if empty array, empty object, or null;
812 /// otherwise, false.
816 bool operator!() const;
818 /// Remove all object members and array elements.
819 /// \pre type() is arrayValue, objectValue, or nullValue
820 /// \post type() is unchanged
823 /// Resize the array to size elements.
824 /// New elements are initialized to null.
825 /// May only be called on nullValue or arrayValue.
826 /// \pre type() is arrayValue or nullValue
827 /// \post type() is arrayValue
828 void resize(ArrayIndex size);
830 /// Access an array element (zero based index ).
831 /// If the array contains less than index element, then null value are
833 /// in the array so that its size is index+1.
834 /// (You may need to say 'value[0u]' to get your compiler to distinguish
835 /// this from the operator[] which takes a string.)
836 Value &operator[](ArrayIndex index);
838 /// Access an array element (zero based index ).
839 /// If the array contains less than index element, then null value are
841 /// in the array so that its size is index+1.
842 /// (You may need to say 'value[0u]' to get your compiler to distinguish
843 /// this from the operator[] which takes a string.)
844 Value &operator[](int index);
846 /// Access an array element (zero based index )
847 /// (You may need to say 'value[0u]' to get your compiler to distinguish
848 /// this from the operator[] which takes a string.)
849 const Value &operator[](ArrayIndex index) const;
851 /// Access an array element (zero based index )
852 /// (You may need to say 'value[0u]' to get your compiler to distinguish
853 /// this from the operator[] which takes a string.)
854 const Value &operator[](int index) const;
856 /// If the array contains at least index+1 elements, returns the element
858 /// otherwise returns defaultValue.
859 Value get(ArrayIndex index, const Value &defaultValue) const;
860 /// Return true if index < size().
861 bool isValidIndex(ArrayIndex index) const;
862 /// \brief Append value to array at the end.
864 /// Equivalent to jsonvalue[jsonvalue.size()] = value;
865 Value &append(const Value &value);
867 /// Access an object value by name, create a null member if it does not exist.
868 /// \note Because of our implementation, keys are limited to 2^30 -1 chars.
869 /// Exceeding that will cause an exception.
870 Value &operator[](const char *key);
871 /// Access an object value by name, returns null if there is no member with
873 const Value &operator[](const char *key) const;
874 /// Access an object value by name, create a null member if it does not exist.
875 /// \param key may contain embedded nulls.
876 Value &operator[](const JSONCPP_STRING &key);
877 /// Access an object value by name, returns null if there is no member with
879 /// \param key may contain embedded nulls.
880 const Value &operator[](const JSONCPP_STRING &key) const;
881 /** \brief Access an object value by name, create a null member if it does not
884 * If the object has no entry for that name, then the member name used to store
885 * the new entry is not duplicated.
888 * Json::Value object;
889 * static const StaticString code("code");
890 * object[code] = 1234;
893 Value &operator[](const StaticString &key);
894 #ifdef JSON_USE_CPPTL
895 /// Access an object value by name, create a null member if it does not exist.
896 Value &operator[](const CppTL::ConstString &key);
897 /// Access an object value by name, returns null if there is no member with
899 const Value &operator[](const CppTL::ConstString &key) const;
901 /// Return the member named key if it exist, defaultValue otherwise.
903 Value get(const char *key, const Value &defaultValue) const;
904 /// Return the member named key if it exist, defaultValue otherwise.
906 /// \note key may contain embedded nulls.
907 Value get(const char *begin, const char *end, const Value &defaultValue) const;
908 /// Return the member named key if it exist, defaultValue otherwise.
910 /// \param key may contain embedded nulls.
911 Value get(const JSONCPP_STRING &key, const Value &defaultValue) const;
912 #ifdef JSON_USE_CPPTL
913 /// Return the member named key if it exist, defaultValue otherwise.
915 Value get(const CppTL::ConstString &key, const Value &defaultValue) const;
917 /// Most general and efficient version of isMember()const, get()const,
918 /// and operator[]const
919 /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
920 Value const *find(char const *begin, char const *end) const;
921 /// Most general and efficient version of object-mutators.
922 /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
923 /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
924 Value const *demand(char const *begin, char const *end);
925 /// \brief Remove and return the named member.
927 /// Do nothing if it did not exist.
928 /// \return the removed Value, or null.
929 /// \pre type() is objectValue or nullValue
930 /// \post type() is unchanged
932 Value removeMember(const char *key);
933 /// Same as removeMember(const char*)
934 /// \param key may contain embedded nulls.
936 Value removeMember(const JSONCPP_STRING &key);
937 /// Same as removeMember(const char* begin, const char* end, Value* removed),
938 /// but 'key' is null-terminated.
939 bool removeMember(const char *key, Value *removed);
940 /** \brief Remove the named map member.
942 Update 'removed' iff removed.
943 \param key may contain embedded nulls.
944 \return true iff removed (no exceptions)
946 bool removeMember(JSONCPP_STRING const &key, Value *removed);
947 /// Same as removeMember(JSONCPP_STRING const& key, Value* removed)
948 bool removeMember(const char *begin, const char *end, Value *removed);
949 /** \brief Remove the indexed array element.
951 O(n) expensive operations.
952 Update 'removed' iff removed.
953 \return true iff removed (no exceptions)
955 bool removeIndex(ArrayIndex i, Value *removed);
957 /// Return true if the object has a member named key.
958 /// \note 'key' must be null-terminated.
959 bool isMember(const char *key) const;
960 /// Return true if the object has a member named key.
961 /// \param key may contain embedded nulls.
962 bool isMember(const JSONCPP_STRING &key) const;
963 /// Same as isMember(JSONCPP_STRING const& key)const
964 bool isMember(const char *begin, const char *end) const;
965 #ifdef JSON_USE_CPPTL
966 /// Return true if the object has a member named key.
967 bool isMember(const CppTL::ConstString &key) const;
970 /// \brief Return a list of the member names.
972 /// If null, return an empty list.
973 /// \pre type() is objectValue or nullValue
974 /// \post if type() was nullValue, it remains nullValue
975 Members getMemberNames() const;
977 //# ifdef JSON_USE_CPPTL
978 // EnumMemberNames enumMemberNames() const;
979 // EnumValues enumValues() const;
982 /// \deprecated Always pass len.
983 JSONCPP_DEPRECATED("Use setComment(JSONCPP_STRING const&) instead.")
984 void setComment(const char *comment, CommentPlacement placement);
985 /// Comments must be //... or /* ... */
986 void setComment(const char *comment, size_t len, CommentPlacement placement);
987 /// Comments must be //... or /* ... */
988 void setComment(const JSONCPP_STRING &comment, CommentPlacement placement);
989 bool hasComment(CommentPlacement placement) const;
990 /// Include delimiters and embedded newlines.
991 JSONCPP_STRING getComment(CommentPlacement placement) const;
993 JSONCPP_STRING toStyledString() const;
995 const_iterator begin() const;
996 const_iterator end() const;
1001 // Accessors for the [start, limit) range of bytes within the JSON text from
1002 // which this value was parsed, if any.
1003 void setOffsetStart(ptrdiff_t start);
1004 void setOffsetLimit(ptrdiff_t limit);
1005 ptrdiff_t getOffsetStart() const;
1006 ptrdiff_t getOffsetLimit() const;
1009 void initBasic(ValueType type, bool allocated = false);
1011 Value &resolveReference(const char *key);
1012 Value &resolveReference(const char *key, const char *end);
1019 void setComment(const char *text, size_t len);
1024 // struct MemberNamesTransform
1026 // typedef const char *result_type;
1027 // const char *operator()( const CZString &name ) const
1029 // return name.c_str();
1038 char *string_; // actually ptr to unsigned, followed by str, unless !allocated_
1041 ValueType type_ : 8;
1042 unsigned int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
1043 // If not allocated_, string_ must be null-terminated.
1044 CommentInfo *comments_;
1046 // [start, limit) byte offsets in the source JSON text from which this Value
1052 /** \brief Experimental and untested: represents an element of the "path" to
1055 class JSON_API PathArgument
1061 PathArgument(ArrayIndex index);
1062 PathArgument(const char *key);
1063 PathArgument(const JSONCPP_STRING &key);
1072 JSONCPP_STRING key_;
1077 /** \brief Experimental and untested: represents a "path" to access a node.
1080 * - "." => root node
1081 * - ".[n]" => elements at index 'n' of root node (an array value)
1082 * - ".name" => member named 'name' of root node (an object value)
1083 * - ".name1.name2.name3"
1084 * - ".[0][1][2].name1[3]"
1085 * - ".%" => member name is provided as parameter
1086 * - ".[%]" => index is provied as parameter
1091 Path(const JSONCPP_STRING &path, const PathArgument &a1 = PathArgument(),
1092 const PathArgument &a2 = PathArgument(), const PathArgument &a3 = PathArgument(),
1093 const PathArgument &a4 = PathArgument(), const PathArgument &a5 = PathArgument());
1095 const Value &resolve(const Value &root) const;
1096 Value resolve(const Value &root, const Value &defaultValue) const;
1097 /// Creates the "path" to access the specified node and returns a reference on
1099 Value &make(Value &root) const;
1102 typedef std::vector<const PathArgument *> InArgs;
1103 typedef std::vector<PathArgument> Args;
1105 void makePath(const JSONCPP_STRING &path, const InArgs &in);
1106 void addPathInArg(const JSONCPP_STRING &path, const InArgs &in, InArgs::const_iterator &itInArg,
1107 PathArgument::Kind kind);
1108 void invalidPath(const JSONCPP_STRING &path, int location);
1113 /** \brief base class for Value iterators.
1116 class JSON_API ValueIteratorBase
1119 typedef std::bidirectional_iterator_tag iterator_category;
1120 typedef unsigned int size_t;
1121 typedef int difference_type;
1122 typedef ValueIteratorBase SelfType;
1124 bool operator==(const SelfType &other) const { return isEqual(other); }
1126 bool operator!=(const SelfType &other) const { return !isEqual(other); }
1128 difference_type operator-(const SelfType &other) const { return other.computeDistance(*this); }
1130 /// Return either the index or the member name of the referenced value as a
1134 /// Return the index of the referenced Value, or -1 if it is not an arrayValue.
1137 /// Return the member name of the referenced Value, or "" if it is not an
1139 /// \note Avoid `c_str()` on result, as embedded zeroes are possible.
1140 JSONCPP_STRING name() const;
1142 /// Return the member name of the referenced Value. "" if it is not an
1144 /// \deprecated This cannot be used for UTF-8 strings, since there can be embedded nulls.
1145 JSONCPP_DEPRECATED("Use `key = name();` instead.")
1146 char const *memberName() const;
1147 /// Return the member name of the referenced Value, or NULL if it is not an
1149 /// \note Better version than memberName(). Allows embedded nulls.
1150 char const *memberName(char const **end) const;
1153 Value &deref() const;
1159 difference_type computeDistance(const SelfType &other) const;
1161 bool isEqual(const SelfType &other) const;
1163 void copy(const SelfType &other);
1166 Value::ObjectValues::iterator current_;
1167 // Indicates that iterator is for a null value.
1171 // For some reason, BORLAND needs these at the end, rather
1172 // than earlier. No idea why.
1173 ValueIteratorBase();
1174 explicit ValueIteratorBase(const Value::ObjectValues::iterator ¤t);
1177 /** \brief const iterator for object and array value.
1180 class JSON_API ValueConstIterator : public ValueIteratorBase
1185 typedef const Value value_type;
1186 // typedef unsigned int size_t;
1187 // typedef int difference_type;
1188 typedef const Value &reference;
1189 typedef const Value *pointer;
1190 typedef ValueConstIterator SelfType;
1192 ValueConstIterator();
1193 ValueConstIterator(ValueIterator const &other);
1196 /*! \internal Use by Value to create an iterator.
1198 explicit ValueConstIterator(const Value::ObjectValues::iterator ¤t);
1201 SelfType &operator=(const ValueIteratorBase &other);
1203 SelfType operator++(int)
1205 SelfType temp(*this);
1210 SelfType operator--(int)
1212 SelfType temp(*this);
1217 SelfType &operator--()
1223 SelfType &operator++()
1229 reference operator*() const { return deref(); }
1231 pointer operator->() const { return &deref(); }
1234 /** \brief Iterator for object and array value.
1236 class JSON_API ValueIterator : public ValueIteratorBase
1241 typedef Value value_type;
1242 typedef unsigned int size_t;
1243 typedef int difference_type;
1244 typedef Value &reference;
1245 typedef Value *pointer;
1246 typedef ValueIterator SelfType;
1249 explicit ValueIterator(const ValueConstIterator &other);
1250 ValueIterator(const ValueIterator &other);
1253 /*! \internal Use by Value to create an iterator.
1255 explicit ValueIterator(const Value::ObjectValues::iterator ¤t);
1258 SelfType &operator=(const SelfType &other);
1260 SelfType operator++(int)
1262 SelfType temp(*this);
1267 SelfType operator--(int)
1269 SelfType temp(*this);
1274 SelfType &operator--()
1280 SelfType &operator++()
1286 reference operator*() const { return deref(); }
1288 pointer operator->() const { return &deref(); }
1295 /// Specialize std::swap() for Json::Value.
1296 template <> inline void swap(Json::Value &a, Json::Value &b) { a.swap(b); }
1299 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1300 #pragma warning(pop)
1301 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1303 #endif // CPPTL_JSON_H_INCLUDED
1305 // //////////////////////////////////////////////////////////////////////
1306 // End of content of file: include/json/value.h
1307 // //////////////////////////////////////////////////////////////////////
1309 // //////////////////////////////////////////////////////////////////////
1310 // Beginning of content of file: include/json/reader.h
1311 // //////////////////////////////////////////////////////////////////////
1313 // Copyright 2007-2010 Baptiste Lepilleur
1314 // Distributed under MIT license, or public domain if desired and
1315 // recognized in your jurisdiction.
1316 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1318 #ifndef CPPTL_JSON_READER_H_INCLUDED
1319 #define CPPTL_JSON_READER_H_INCLUDED
1321 #if !defined(JSON_IS_AMALGAMATION)
1322 #include "features.h"
1324 #endif // if !defined(JSON_IS_AMALGAMATION)
1331 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
1333 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1334 #pragma warning(push)
1335 #pragma warning(disable : 4251)
1336 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1341 /** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a
1344 * \deprecated Use CharReader and CharReaderBuilder.
1346 class JSON_API Reader
1350 typedef const Char *Location;
1352 /** \brief An error tagged with where in the JSON text it was encountered.
1354 * The offsets give the [start, limit) range of bytes within the text. Note
1355 * that this is bytes, not codepoints.
1358 struct StructuredError
1360 ptrdiff_t offset_start;
1361 ptrdiff_t offset_limit;
1362 JSONCPP_STRING message;
1365 /** \brief Constructs a Reader allowing all features
1370 /** \brief Constructs a Reader allowing the specified feature set
1373 Reader(const Features &features);
1375 /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1377 * \param document UTF-8 encoded string containing the document to read.
1378 * \param root [out] Contains the root value of the document if it was
1379 * successfully parsed.
1380 * \param collectComments \c true to collect comment and allow writing them
1382 * serialization, \c false to discard comments.
1383 * This parameter is ignored if
1384 * Features::allowComments_
1386 * \return \c true if the document was successfully parsed, \c false if an
1389 bool parse(const std::string &document, Value &root, bool collectComments = true);
1391 /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1393 * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
1395 * \param endDoc Pointer on the end of the UTF-8 encoded string of the
1397 * Must be >= beginDoc.
1398 * \param root [out] Contains the root value of the document if it was
1399 * successfully parsed.
1400 * \param collectComments \c true to collect comment and allow writing them
1402 * serialization, \c false to discard comments.
1403 * This parameter is ignored if
1404 Features::allowComments_
1406 * \return \c true if the document was successfully parsed, \c false if an
1409 bool parse(const char *beginDoc, const char *endDoc, Value &root, bool collectComments = true);
1411 /// \brief Parse from input stream.
1412 /// \see Json::operator>>(std::istream&, Json::Value&).
1413 bool parse(JSONCPP_ISTREAM &is, Value &root, bool collectComments = true);
1415 /** \brief Returns a user friendly string that list errors in the parsed
1417 * \return Formatted error message with the list of errors with their location
1419 * the parsed document. An empty string is returned if no error
1422 * \deprecated Use getFormattedErrorMessages() instead (typo fix).
1424 JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.")
1425 JSONCPP_STRING getFormatedErrorMessages() const;
1427 /** \brief Returns a user friendly string that list errors in the parsed
1429 * \return Formatted error message with the list of errors with their location
1431 * the parsed document. An empty string is returned if no error
1435 JSONCPP_STRING getFormattedErrorMessages() const;
1437 /** \brief Returns a vector of structured erros encounted while parsing.
1438 * \return A (possibly empty) vector of StructuredError objects. Currently
1439 * only one error can be returned, but the caller should tolerate
1441 * errors. This can occur if the parser recovers from a non-fatal
1442 * parse error and then encounters additional errors.
1444 std::vector<StructuredError> getStructuredErrors() const;
1446 /** \brief Add a semantic error message.
1447 * \param value JSON Value location associated with the error
1448 * \param message The error message.
1449 * \return \c true if the error was successfully added, \c false if the
1450 * Value offset exceeds the document size.
1452 bool pushError(const Value &value, const JSONCPP_STRING &message);
1454 /** \brief Add a semantic error message with extra context.
1455 * \param value JSON Value location associated with the error
1456 * \param message The error message.
1457 * \param extra Additional JSON Value location to contextualize the error
1458 * \return \c true if the error was successfully added, \c false if either
1459 * Value offset exceeds the document size.
1461 bool pushError(const Value &value, const JSONCPP_STRING &message, const Value &extra);
1463 /** \brief Return whether there are any errors.
1464 * \return \c true if there are no errors to report \c false if
1465 * errors have occurred.
1472 tokenEndOfStream = 0,
1482 tokenArraySeparator,
1483 tokenMemberSeparator,
1500 JSONCPP_STRING message_;
1504 typedef std::deque<ErrorInfo> Errors;
1506 bool readToken(Token &token);
1508 bool match(Location pattern, int patternLength);
1510 bool readCStyleComment();
1511 bool readCppStyleComment();
1515 bool readObject(Token &token);
1516 bool readArray(Token &token);
1517 bool decodeNumber(Token &token);
1518 bool decodeNumber(Token &token, Value &decoded);
1519 bool decodeString(Token &token);
1520 bool decodeString(Token &token, JSONCPP_STRING &decoded);
1521 bool decodeDouble(Token &token);
1522 bool decodeDouble(Token &token, Value &decoded);
1523 bool decodeUnicodeCodePoint(Token &token, Location ¤t, Location end, unsigned int &unicode);
1524 bool decodeUnicodeEscapeSequence(Token &token, Location ¤t, Location end,
1525 unsigned int &unicode);
1526 bool addError(const JSONCPP_STRING &message, Token &token, Location extra = 0);
1527 bool recoverFromError(TokenType skipUntilToken);
1528 bool addErrorAndRecover(const JSONCPP_STRING &message, Token &token, TokenType skipUntilToken);
1529 void skipUntilSpace();
1530 Value ¤tValue();
1532 void getLocationLineAndColumn(Location location, int &line, int &column) const;
1533 JSONCPP_STRING getLocationLineAndColumn(Location location) const;
1534 void addComment(Location begin, Location end, CommentPlacement placement);
1535 void skipCommentTokens(Token &token);
1537 typedef std::stack<Value *> Nodes;
1540 JSONCPP_STRING document_;
1544 Location lastValueEnd_;
1546 JSONCPP_STRING commentsBefore_;
1548 bool collectComments_;
1551 /** Interface for reading JSON from a char array.
1553 class JSON_API CharReader
1556 virtual ~CharReader() {}
1557 /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1559 * The document must be a UTF-8 encoded string containing the document to read.
1561 * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
1563 * \param endDoc Pointer on the end of the UTF-8 encoded string of the
1565 * Must be >= beginDoc.
1566 * \param root [out] Contains the root value of the document if it was
1567 * successfully parsed.
1568 * \param errs [out] Formatted error messages (if not NULL)
1569 * a user friendly string that lists errors in the parsed
1571 * \return \c true if the document was successfully parsed, \c false if an
1574 virtual bool parse(char const *beginDoc, char const *endDoc, Value *root,
1575 JSONCPP_STRING *errs) = 0;
1577 class JSON_API Factory
1580 virtual ~Factory() {}
1581 /** \brief Allocate a CharReader via operator new().
1582 * \throw std::exception if something goes wrong (e.g. invalid settings)
1584 virtual CharReader *newCharReader() const = 0;
1588 /** \brief Build a CharReader implementation.
1592 using namespace Json;
1593 CharReaderBuilder builder;
1594 builder["collectComments"] = false;
1596 JSONCPP_STRING errs;
1597 bool ok = parseFromStream(builder, std::cin, &value, &errs);
1600 class JSON_API CharReaderBuilder : public CharReader::Factory
1603 // Note: We use a Json::Value so that we can add data-members to this class
1604 // without a major version bump.
1605 /** Configuration of this builder.
1606 These are case-sensitive.
1607 Available settings (case-sensitive):
1608 - `"collectComments": false or true`
1609 - true to collect comment and allow writing them
1610 back during serialization, false to discard comments.
1611 This parameter is ignored if allowComments is false.
1612 - `"allowComments": false or true`
1613 - true if comments are allowed.
1614 - `"strictRoot": false or true`
1615 - true if root must be either an array or an object value
1616 - `"allowDroppedNullPlaceholders": false or true`
1617 - true if dropped null placeholders are allowed. (See StreamWriterBuilder.)
1618 - `"allowNumericKeys": false or true`
1619 - true if numeric object keys are allowed.
1620 - `"allowSingleQuotes": false or true`
1621 - true if '' are allowed for strings (both keys and values)
1622 - `"stackLimit": integer`
1623 - Exceeding stackLimit (recursive depth of `readValue()`) will
1625 - This is a security issue (seg-faults caused by deeply nested JSON),
1626 so the default is low.
1627 - `"failIfExtra": false or true`
1628 - If true, `parse()` returns false when extra non-whitespace trails
1629 the JSON value in the input string.
1630 - `"rejectDupKeys": false or true`
1631 - If true, `parse()` returns false when a key is duplicated within an object.
1632 - `"allowSpecialFloats": false or true`
1633 - If true, special float values (NaNs and infinities) are allowed
1634 and their values are lossfree restorable.
1636 You can examine 'settings_` yourself
1637 to see the defaults. You can also write and read them just like any
1641 Json::Value settings_;
1643 CharReaderBuilder();
1644 ~CharReaderBuilder() JSONCPP_OVERRIDE;
1646 CharReader *newCharReader() const JSONCPP_OVERRIDE;
1648 /** \return true if 'settings' are legal and consistent;
1649 * otherwise, indicate bad settings via 'invalid'.
1651 bool validate(Json::Value *invalid) const;
1653 /** A simple way to update a specific setting.
1655 Value &operator[](JSONCPP_STRING key);
1657 /** Called by ctor, but you can use this to reset settings_.
1658 * \pre 'settings' != NULL (but Json::null is fine)
1660 * \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults
1662 static void setDefaults(Json::Value *settings);
1663 /** Same as old Features::strictMode().
1664 * \pre 'settings' != NULL (but Json::null is fine)
1666 * \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode
1668 static void strictMode(Json::Value *settings);
1671 /** Consume entire stream and use its begin/end.
1672 * Someday we might have a real StreamReader, but for now this
1675 bool JSON_API parseFromStream(CharReader::Factory const &, JSONCPP_ISTREAM &, Value *root,
1678 /** \brief Read from 'sin' into 'root'.
1680 Always keep comments from the input JSON.
1682 This can be used to read a file into a particular sub-object.
1686 cin >> root["dir"]["file"];
1694 // The input stream JSON would be nested here.
1699 \throw std::exception on parse error.
1700 \see Json::operator<<()
1702 JSON_API JSONCPP_ISTREAM &operator>>(JSONCPP_ISTREAM &, Value &);
1706 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1707 #pragma warning(pop)
1708 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1710 #endif // CPPTL_JSON_READER_H_INCLUDED
1712 // //////////////////////////////////////////////////////////////////////
1713 // End of content of file: include/json/reader.h
1714 // //////////////////////////////////////////////////////////////////////
1716 // //////////////////////////////////////////////////////////////////////
1717 // Beginning of content of file: include/json/writer.h
1718 // //////////////////////////////////////////////////////////////////////
1720 // Copyright 2007-2010 Baptiste Lepilleur
1721 // Distributed under MIT license, or public domain if desired and
1722 // recognized in your jurisdiction.
1723 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1725 #ifndef JSON_WRITER_H_INCLUDED
1726 #define JSON_WRITER_H_INCLUDED
1728 #if !defined(JSON_IS_AMALGAMATION)
1730 #endif // if !defined(JSON_IS_AMALGAMATION)
1735 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
1737 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1738 #pragma warning(push)
1739 #pragma warning(disable : 4251)
1740 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1751 using namespace Json;
1752 void writeToStdout(StreamWriter::Factory const& factory, Value const& value) {
1753 std::unique_ptr<StreamWriter> const writer(
1754 factory.newStreamWriter());
1755 writer->write(value, &std::cout);
1756 std::cout << std::endl; // add lf and flush
1760 class JSON_API StreamWriter
1763 JSONCPP_OSTREAM *sout_; // not owned; will not delete
1766 virtual ~StreamWriter();
1767 /** Write Value into document as configured in sub-class.
1768 Do not take ownership of sout, but maintain a reference during function.
1770 \return zero on success (For now, we always return zero, so check the stream instead.)
1771 \throw std::exception possibly, depending on configuration
1773 virtual int write(Value const &root, JSONCPP_OSTREAM *sout) = 0;
1775 /** \brief A simple abstract factory.
1777 class JSON_API Factory
1781 /** \brief Allocate a CharReader via operator new().
1782 * \throw std::exception if something goes wrong (e.g. invalid settings)
1784 virtual StreamWriter *newStreamWriter() const = 0;
1788 /** \brief Write into stringstream, then return string, for convenience.
1789 * A StreamWriter will be created from the factory, used, and then deleted.
1791 JSONCPP_STRING JSON_API writeString(StreamWriter::Factory const &factory, Value const &root);
1793 /** \brief Build a StreamWriter implementation.
1797 using namespace Json;
1799 StreamWriterBuilder builder;
1800 builder["commentStyle"] = "None";
1801 builder["indentation"] = " "; // or whatever you like
1802 std::unique_ptr<Json::StreamWriter> writer(
1803 builder.newStreamWriter());
1804 writer->write(value, &std::cout);
1805 std::cout << std::endl; // add lf and flush
1808 class JSON_API StreamWriterBuilder : public StreamWriter::Factory
1811 // Note: We use a Json::Value so that we can add data-members to this class
1812 // without a major version bump.
1813 /** Configuration of this builder.
1814 Available settings (case-sensitive):
1815 - "commentStyle": "None" or "All"
1816 - "indentation": "<anything>"
1817 - "enableYAMLCompatibility": false or true
1818 - slightly change the whitespace around colons
1819 - "dropNullPlaceholders": false or true
1820 - Drop the "null" string from the writer's output for nullValues.
1821 Strictly speaking, this is not valid JSON. But when the output is being
1822 fed to a browser's Javascript, it makes for smaller output and the
1823 browser can handle the output just fine.
1824 - "useSpecialFloats": false or true
1825 - If true, outputs non-finite floating point values in the following way:
1826 NaN values as "NaN", positive infinity as "Infinity", and negative infinity
1829 You can examine 'settings_` yourself
1830 to see the defaults. You can also write and read them just like any
1834 Json::Value settings_;
1836 StreamWriterBuilder();
1837 ~StreamWriterBuilder() JSONCPP_OVERRIDE;
1840 * \throw std::exception if something goes wrong (e.g. invalid settings)
1842 StreamWriter *newStreamWriter() const JSONCPP_OVERRIDE;
1844 /** \return true if 'settings' are legal and consistent;
1845 * otherwise, indicate bad settings via 'invalid'.
1847 bool validate(Json::Value *invalid) const;
1848 /** A simple way to update a specific setting.
1850 Value &operator[](JSONCPP_STRING key);
1852 /** Called by ctor, but you can use this to reset settings_.
1853 * \pre 'settings' != NULL (but Json::null is fine)
1855 * \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults
1857 static void setDefaults(Json::Value *settings);
1860 /** \brief Abstract class for writers.
1861 * \deprecated Use StreamWriter. (And really, this is an implementation detail.)
1863 class JSON_API Writer
1868 virtual JSONCPP_STRING write(const Value &root) = 0;
1871 /** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format
1872 *without formatting (not human friendly).
1874 * The JSON document is written in a single line. It is not intended for 'human'
1876 * but may be usefull to support feature such as RPC where bandwith is limited.
1878 * \deprecated Use StreamWriterBuilder.
1880 class JSON_API FastWriter : public Writer
1885 ~FastWriter() JSONCPP_OVERRIDE {}
1887 void enableYAMLCompatibility();
1889 /** \brief Drop the "null" string from the writer's output for nullValues.
1890 * Strictly speaking, this is not valid JSON. But when the output is being
1891 * fed to a browser's Javascript, it makes for smaller output and the
1892 * browser can handle the output just fine.
1894 void dropNullPlaceholders();
1896 void omitEndingLineFeed();
1898 public: // overridden from Writer
1899 JSONCPP_STRING write(const Value &root) JSONCPP_OVERRIDE;
1902 void writeValue(const Value &value);
1904 JSONCPP_STRING document_;
1905 bool yamlCompatiblityEnabled_;
1906 bool dropNullPlaceholders_;
1907 bool omitEndingLineFeed_;
1910 /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
1911 *human friendly way.
1913 * The rules for line break and indent are as follow:
1915 * - if empty then print {} without indent and line break
1916 * - if not empty the print '{', line break & indent, print one value per
1918 * and then unindent and line break and print '}'.
1920 * - if empty then print [] without indent and line break
1921 * - if the array contains no object value, empty array or some other value
1923 * and all the values fit on one lines, then print the array on a single
1925 * - otherwise, it the values do not fit on one line, or the array contains
1926 * object or non empty array, then print one value per line.
1928 * If the Value have comments then they are outputed according to their
1931 * \sa Reader, Value, Value::setComment()
1932 * \deprecated Use StreamWriterBuilder.
1934 class JSON_API StyledWriter : public Writer
1938 ~StyledWriter() JSONCPP_OVERRIDE {}
1940 public: // overridden from Writer
1941 /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
1942 * \param root Value to serialize.
1943 * \return String containing the JSON document that represents the root value.
1945 JSONCPP_STRING write(const Value &root) JSONCPP_OVERRIDE;
1948 void writeValue(const Value &value);
1949 void writeArrayValue(const Value &value);
1950 bool isMultineArray(const Value &value);
1951 void pushValue(const JSONCPP_STRING &value);
1953 void writeWithIndent(const JSONCPP_STRING &value);
1956 void writeCommentBeforeValue(const Value &root);
1957 void writeCommentAfterValueOnSameLine(const Value &root);
1958 bool hasCommentForValue(const Value &value);
1959 static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING &text);
1961 typedef std::vector<JSONCPP_STRING> ChildValues;
1963 ChildValues childValues_;
1964 JSONCPP_STRING document_;
1965 JSONCPP_STRING indentString_;
1966 unsigned int rightMargin_;
1967 unsigned int indentSize_;
1968 bool addChildValues_;
1971 /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
1973 to a stream rather than to a string.
1975 * The rules for line break and indent are as follow:
1977 * - if empty then print {} without indent and line break
1978 * - if not empty the print '{', line break & indent, print one value per
1980 * and then unindent and line break and print '}'.
1982 * - if empty then print [] without indent and line break
1983 * - if the array contains no object value, empty array or some other value
1985 * and all the values fit on one lines, then print the array on a single
1987 * - otherwise, it the values do not fit on one line, or the array contains
1988 * object or non empty array, then print one value per line.
1990 * If the Value have comments then they are outputed according to their
1993 * \param indentation Each level will be indented by this amount extra.
1994 * \sa Reader, Value, Value::setComment()
1995 * \deprecated Use StreamWriterBuilder.
1997 class JSON_API StyledStreamWriter
2000 StyledStreamWriter(JSONCPP_STRING indentation = "\t");
2001 ~StyledStreamWriter() {}
2004 /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
2005 * \param out Stream to write to. (Can be ostringstream, e.g.)
2006 * \param root Value to serialize.
2007 * \note There is no point in deriving from Writer, since write() should not
2010 void write(JSONCPP_OSTREAM &out, const Value &root);
2013 void writeValue(const Value &value);
2014 void writeArrayValue(const Value &value);
2015 bool isMultineArray(const Value &value);
2016 void pushValue(const JSONCPP_STRING &value);
2018 void writeWithIndent(const JSONCPP_STRING &value);
2021 void writeCommentBeforeValue(const Value &root);
2022 void writeCommentAfterValueOnSameLine(const Value &root);
2023 bool hasCommentForValue(const Value &value);
2024 static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING &text);
2026 typedef std::vector<JSONCPP_STRING> ChildValues;
2028 ChildValues childValues_;
2029 JSONCPP_OSTREAM *document_;
2030 JSONCPP_STRING indentString_;
2031 unsigned int rightMargin_;
2032 JSONCPP_STRING indentation_;
2033 bool addChildValues_ : 1;
2037 #if defined(JSON_HAS_INT64)
2038 JSONCPP_STRING JSON_API valueToString(Int value);
2039 JSONCPP_STRING JSON_API valueToString(UInt value);
2040 #endif // if defined(JSON_HAS_INT64)
2041 JSONCPP_STRING JSON_API valueToString(LargestInt value);
2042 JSONCPP_STRING JSON_API valueToString(LargestUInt value);
2043 JSONCPP_STRING JSON_API valueToString(double value);
2044 JSONCPP_STRING JSON_API valueToString(bool value);
2045 JSONCPP_STRING JSON_API valueToQuotedString(const char *value);
2047 /// \brief Output using the StyledStreamWriter.
2048 /// \see Json::operator>>()
2049 JSON_API JSONCPP_OSTREAM &operator<<(JSONCPP_OSTREAM &, const Value &root);
2053 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
2054 #pragma warning(pop)
2055 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
2057 #endif // JSON_WRITER_H_INCLUDED
2059 // //////////////////////////////////////////////////////////////////////
2060 // End of content of file: include/json/writer.h
2061 // //////////////////////////////////////////////////////////////////////
2063 // //////////////////////////////////////////////////////////////////////
2064 // Beginning of content of file: include/json/assertions.h
2065 // //////////////////////////////////////////////////////////////////////
2067 // Copyright 2007-2010 Baptiste Lepilleur
2068 // Distributed under MIT license, or public domain if desired and
2069 // recognized in your jurisdiction.
2070 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
2072 #ifndef CPPTL_JSON_ASSERTIONS_H_INCLUDED
2073 #define CPPTL_JSON_ASSERTIONS_H_INCLUDED
2078 #if !defined(JSON_IS_AMALGAMATION)
2080 #endif // if !defined(JSON_IS_AMALGAMATION)
2082 /** It should not be possible for a maliciously designed file to
2083 * cause an abort() or seg-fault, so these macros are used only
2084 * for pre-condition violations and internal logic errors.
2086 #if JSON_USE_EXCEPTION
2088 // @todo <= add detail about condition in exception
2089 #define JSON_ASSERT(condition) \
2093 Json::throwLogicError("assert json failed"); \
2097 #define JSON_FAIL_MESSAGE(message) \
2099 JSONCPP_OSTRINGSTREAM oss; \
2101 Json::throwLogicError(oss.str()); \
2105 #else // JSON_USE_EXCEPTION
2107 #define JSON_ASSERT(condition) assert(condition)
2109 // The call to assert() will show the failure message in debug builds. In
2110 // release builds we abort, for a core-dump or debugger.
2111 #define JSON_FAIL_MESSAGE(message) \
2113 JSONCPP_OSTRINGSTREAM oss; \
2115 assert(false && oss.str().c_str()); \
2121 #define JSON_ASSERT_MESSAGE(condition, message) \
2124 JSON_FAIL_MESSAGE(message); \
2127 #endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED
2129 // //////////////////////////////////////////////////////////////////////
2130 // End of content of file: include/json/assertions.h
2131 // //////////////////////////////////////////////////////////////////////
2133 #endif // ifndef JSON_AMALGATED_H_INCLUDED