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 // //////////////////////////////////////////////////////////////////////
75 #ifndef JSON_AMALGATED_H_INCLUDED
76 # define JSON_AMALGATED_H_INCLUDED
77 /// If defined, indicates that the source file is amalgated
78 /// to prevent private header inclusion.
79 #define JSON_IS_AMALGAMATION
81 // //////////////////////////////////////////////////////////////////////
82 // Beginning of content of file: include/json/version.h
83 // //////////////////////////////////////////////////////////////////////
85 // DO NOT EDIT. This file (and "version") is generated by CMake.
86 // Run CMake configure step to update it.
87 #ifndef JSON_VERSION_H_INCLUDED
88 # define JSON_VERSION_H_INCLUDED
90 # define JSONCPP_VERSION_STRING "1.8.0"
91 # define JSONCPP_VERSION_MAJOR 1
92 # define JSONCPP_VERSION_MINOR 8
93 # define JSONCPP_VERSION_PATCH 0
94 # define JSONCPP_VERSION_QUALIFIER
95 # define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8))
97 #ifdef JSONCPP_USING_SECURE_MEMORY
98 #undef JSONCPP_USING_SECURE_MEMORY
100 #define JSONCPP_USING_SECURE_MEMORY 0
101 // If non-zero, the library zeroes any memory that it has allocated before
102 // it frees its memory.
104 #endif // JSON_VERSION_H_INCLUDED
106 // //////////////////////////////////////////////////////////////////////
107 // End of content of file: include/json/version.h
108 // //////////////////////////////////////////////////////////////////////
115 // //////////////////////////////////////////////////////////////////////
116 // Beginning of content of file: include/json/config.h
117 // //////////////////////////////////////////////////////////////////////
119 // Copyright 2007-2010 Baptiste Lepilleur
120 // Distributed under MIT license, or public domain if desired and
121 // recognized in your jurisdiction.
122 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
124 #ifndef JSON_CONFIG_H_INCLUDED
125 #define JSON_CONFIG_H_INCLUDED
127 #include <string> //typedef String
128 #include <stdint.h> //typedef int64_t, uint64_t
130 /// If defined, indicates that json library is embedded in CppTL library.
131 //# define JSON_IN_CPPTL 1
133 /// If defined, indicates that json may leverage CppTL library
134 //# define JSON_USE_CPPTL 1
135 /// If defined, indicates that cpptl vector based map should be used instead of
137 /// as Value container.
138 //# define JSON_USE_CPPTL_SMALLMAP 1
140 // If non-zero, the library uses exceptions to report bad input instead of C
141 // assertion macros. The default is to use exceptions.
142 #ifndef JSON_USE_EXCEPTION
143 #define JSON_USE_EXCEPTION 1
146 /// If defined, indicates that the source file is amalgated
147 /// to prevent private header inclusion.
148 /// Remarks: it is automatically defined in the generated amalgated header.
149 // #define JSON_IS_AMALGAMATION
152 #include <cpptl/config.h>
153 #ifndef JSON_USE_CPPTL
154 #define JSON_USE_CPPTL 1
159 #define JSON_API CPPTL_API
160 #elif defined(JSON_DLL_BUILD)
161 #if defined(_MSC_VER) || defined(__MINGW32__)
162 #define JSON_API __declspec(dllexport)
163 #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
164 #endif // if defined(_MSC_VER)
165 #elif defined(JSON_DLL)
166 #if defined(_MSC_VER) || defined(__MINGW32__)
167 #define JSON_API __declspec(dllimport)
168 #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
169 #endif // if defined(_MSC_VER)
170 #endif // ifdef JSON_IN_CPPTL
171 #if !defined(JSON_API)
175 // If JSON_NO_INT64 is defined, then Json only support C++ "int" type for
177 // Storages, and 64 bits integer support is disabled.
178 // #define JSON_NO_INT64 1
180 #if defined(_MSC_VER) // MSVC
181 # if _MSC_VER <= 1200 // MSVC 6
182 // Microsoft Visual Studio 6 only support conversion from __int64 to double
183 // (no conversion from unsigned __int64).
184 # define JSON_USE_INT64_DOUBLE_CONVERSION 1
185 // Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255'
186 // characters in the debug information)
187 // All projects I've ever seen with VS6 were using this globally (not bothering
188 // with pragma push/pop).
189 # pragma warning(disable : 4786)
192 # if _MSC_VER >= 1500 // MSVC 2008
193 /// Indicates that the following function is deprecated.
194 # define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
197 #endif // defined(_MSC_VER)
199 // In c++11 the override keyword allows you to explicity define that a function
200 // is intended to override the base-class version. This makes the code more
201 // managable and fixes a set of common hard-to-find bugs.
202 #if __cplusplus >= 201103L
203 # define JSONCPP_OVERRIDE override
204 # define JSONCPP_NOEXCEPT noexcept
205 #elif defined(_MSC_VER) && _MSC_VER > 1600 && _MSC_VER < 1900
206 # define JSONCPP_OVERRIDE override
207 # define JSONCPP_NOEXCEPT throw()
208 #elif defined(_MSC_VER) && _MSC_VER >= 1900
209 # define JSONCPP_OVERRIDE override
210 # define JSONCPP_NOEXCEPT noexcept
212 # define JSONCPP_OVERRIDE
213 # define JSONCPP_NOEXCEPT throw()
216 #ifndef JSON_HAS_RVALUE_REFERENCES
218 #if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010
219 #define JSON_HAS_RVALUE_REFERENCES 1
220 #endif // MSVC >= 2010
223 #if __has_feature(cxx_rvalue_references)
224 #define JSON_HAS_RVALUE_REFERENCES 1
225 #endif // has_feature
227 #elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
228 #if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L)
229 #define JSON_HAS_RVALUE_REFERENCES 1
230 #endif // GXX_EXPERIMENTAL
232 #endif // __clang__ || __GNUC__
234 #endif // not defined JSON_HAS_RVALUE_REFERENCES
236 #ifndef JSON_HAS_RVALUE_REFERENCES
237 #define JSON_HAS_RVALUE_REFERENCES 0
241 #elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
242 # if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
243 # define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
244 # elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
245 # define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__))
246 # endif // GNUC version
247 #endif // __clang__ || __GNUC__
249 #if !defined(JSONCPP_DEPRECATED)
250 #define JSONCPP_DEPRECATED(message)
251 #endif // if !defined(JSONCPP_DEPRECATED)
254 # define JSON_USE_INT64_DOUBLE_CONVERSION 1
257 #if !defined(JSON_IS_AMALGAMATION)
259 # include "version.h"
261 # if JSONCPP_USING_SECURE_MEMORY
262 # include "allocator.h" //typedef Allocator
265 #endif // if !defined(JSON_IS_AMALGAMATION)
269 typedef unsigned int UInt;
270 #if defined(JSON_NO_INT64)
271 typedef int LargestInt;
272 typedef unsigned int LargestUInt;
273 #undef JSON_HAS_INT64
274 #else // if defined(JSON_NO_INT64)
275 // For Microsoft Visual use specific types as long long is not supported
276 #if defined(_MSC_VER) // Microsoft Visual Studio
277 typedef __int64 Int64;
278 typedef unsigned __int64 UInt64;
279 #else // if defined(_MSC_VER) // Other platforms, use long long
280 typedef int64_t Int64;
281 typedef uint64_t UInt64;
282 #endif // if defined(_MSC_VER)
283 typedef Int64 LargestInt;
284 typedef UInt64 LargestUInt;
285 #define JSON_HAS_INT64
286 #endif // if defined(JSON_NO_INT64)
287 #if JSONCPP_USING_SECURE_MEMORY
288 #define JSONCPP_STRING std::basic_string<char, std::char_traits<char>, Json::SecureAllocator<char> >
289 #define JSONCPP_OSTRINGSTREAM std::basic_ostringstream<char, std::char_traits<char>, Json::SecureAllocator<char> >
290 #define JSONCPP_OSTREAM std::basic_ostream<char, std::char_traits<char>>
291 #define JSONCPP_ISTRINGSTREAM std::basic_istringstream<char, std::char_traits<char>, Json::SecureAllocator<char> >
292 #define JSONCPP_ISTREAM std::istream
294 #define JSONCPP_STRING std::string
295 #define JSONCPP_OSTRINGSTREAM std::ostringstream
296 #define JSONCPP_OSTREAM std::ostream
297 #define JSONCPP_ISTRINGSTREAM std::istringstream
298 #define JSONCPP_ISTREAM std::istream
299 #endif // if JSONCPP_USING_SECURE_MEMORY
300 } // end namespace Json
302 #endif // JSON_CONFIG_H_INCLUDED
304 // //////////////////////////////////////////////////////////////////////
305 // End of content of file: include/json/config.h
306 // //////////////////////////////////////////////////////////////////////
313 // //////////////////////////////////////////////////////////////////////
314 // Beginning of content of file: include/json/forwards.h
315 // //////////////////////////////////////////////////////////////////////
317 // Copyright 2007-2010 Baptiste Lepilleur
318 // Distributed under MIT license, or public domain if desired and
319 // recognized in your jurisdiction.
320 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
322 #ifndef JSON_FORWARDS_H_INCLUDED
323 #define JSON_FORWARDS_H_INCLUDED
325 #if !defined(JSON_IS_AMALGAMATION)
327 #endif // if !defined(JSON_IS_AMALGAMATION)
342 typedef unsigned int ArrayIndex;
347 class ValueIteratorBase;
349 class ValueConstIterator;
353 #endif // JSON_FORWARDS_H_INCLUDED
355 // //////////////////////////////////////////////////////////////////////
356 // End of content of file: include/json/forwards.h
357 // //////////////////////////////////////////////////////////////////////
364 // //////////////////////////////////////////////////////////////////////
365 // Beginning of content of file: include/json/features.h
366 // //////////////////////////////////////////////////////////////////////
368 // Copyright 2007-2010 Baptiste Lepilleur
369 // Distributed under MIT license, or public domain if desired and
370 // recognized in your jurisdiction.
371 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
373 #ifndef CPPTL_JSON_FEATURES_H_INCLUDED
374 #define CPPTL_JSON_FEATURES_H_INCLUDED
376 #if !defined(JSON_IS_AMALGAMATION)
377 #include "forwards.h"
378 #endif // if !defined(JSON_IS_AMALGAMATION)
380 #pragma pack(push, 8)
384 /** \brief Configuration passed to reader and writer.
385 * This configuration object can be used to force the Reader or Writer
386 * to behave in a standard conforming way.
388 class JSON_API Features {
390 /** \brief A configuration that allows all features and assumes all strings
392 * - C & C++ comments are allowed
393 * - Root object can be any JSON value
394 * - Assumes Value strings are encoded in UTF-8
396 static Features all();
398 /** \brief A configuration that is strictly compatible with the JSON
400 * - Comments are forbidden.
401 * - Root object must be either an array or an object value.
402 * - Assumes Value strings are encoded in UTF-8
404 static Features strictMode();
406 /** \brief Initialize the configuration like JsonConfig::allFeatures;
410 /// \c true if comments are allowed. Default: \c true.
413 /// \c true if root must be either an array or an object value. Default: \c
417 /// \c true if dropped null placeholders are allowed. Default: \c false.
418 bool allowDroppedNullPlaceholders_;
420 /// \c true if numeric object key are allowed. Default: \c false.
421 bool allowNumericKeys_;
428 #endif // CPPTL_JSON_FEATURES_H_INCLUDED
430 // //////////////////////////////////////////////////////////////////////
431 // End of content of file: include/json/features.h
432 // //////////////////////////////////////////////////////////////////////
439 // //////////////////////////////////////////////////////////////////////
440 // Beginning of content of file: include/json/value.h
441 // //////////////////////////////////////////////////////////////////////
443 // Copyright 2007-2010 Baptiste Lepilleur
444 // Distributed under MIT license, or public domain if desired and
445 // recognized in your jurisdiction.
446 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
448 #ifndef CPPTL_JSON_H_INCLUDED
449 #define CPPTL_JSON_H_INCLUDED
451 #if !defined(JSON_IS_AMALGAMATION)
452 #include "forwards.h"
453 #endif // if !defined(JSON_IS_AMALGAMATION)
458 #ifndef JSON_USE_CPPTL_SMALLMAP
461 #include <cpptl/smallmap.h>
463 #ifdef JSON_USE_CPPTL
464 #include <cpptl/forwards.h>
467 //Conditional NORETURN attribute on the throw functions would:
468 // a) suppress false positives from static code analysis
469 // b) possibly improve optimization opportunities.
470 #if !defined(JSONCPP_NORETURN)
471 # if defined(_MSC_VER)
472 # define JSONCPP_NORETURN __declspec(noreturn)
473 # elif defined(__GNUC__)
474 # define JSONCPP_NORETURN __attribute__ ((__noreturn__))
476 # define JSONCPP_NORETURN
480 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
482 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
483 #pragma warning(push)
484 #pragma warning(disable : 4251)
485 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
487 #pragma pack(push, 8)
489 /** \brief JSON (JavaScript Object Notation).
493 /** Base class for all exceptions we throw.
495 * We use nothing but these internally. Of course, STL can throw others.
497 class JSON_API Exception : public std::exception {
499 Exception(JSONCPP_STRING const& msg);
500 ~Exception() JSONCPP_NOEXCEPT JSONCPP_OVERRIDE;
501 char const* what() const JSONCPP_NOEXCEPT JSONCPP_OVERRIDE;
506 /** Exceptions which the user cannot easily avoid.
508 * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
510 * \remark derived from Json::Exception
512 class JSON_API RuntimeError : public Exception {
514 RuntimeError(JSONCPP_STRING const& msg);
517 /** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
519 * These are precondition-violations (user bugs) and internal errors (our bugs).
521 * \remark derived from Json::Exception
523 class JSON_API LogicError : public Exception {
525 LogicError(JSONCPP_STRING const& msg);
529 JSONCPP_NORETURN void throwRuntimeError(JSONCPP_STRING const& msg);
531 JSONCPP_NORETURN void throwLogicError(JSONCPP_STRING const& msg);
533 /** \brief Type of the value held by a Value object.
536 nullValue = 0, ///< 'null' value
537 intValue, ///< signed integer value
538 uintValue, ///< unsigned integer value
539 realValue, ///< double value
540 stringValue, ///< UTF-8 string value
541 booleanValue, ///< bool value
542 arrayValue, ///< array value (ordered list)
543 objectValue ///< object value (collection of name/value pairs).
546 enum CommentPlacement {
547 commentBefore = 0, ///< a comment placed on the line before a value
548 commentAfterOnSameLine, ///< a comment just after a value on the same line
549 commentAfter, ///< a comment on the line after a value (only make sense for
551 numberOfCommentPlacement
554 //# ifdef JSON_USE_CPPTL
555 // typedef CppTL::AnyEnumerator<const char *> EnumMemberNames;
556 // typedef CppTL::AnyEnumerator<const Value &> EnumValues;
559 /** \brief Lightweight wrapper to tag static string.
561 * Value constructor and objectValue member assignement takes advantage of the
562 * StaticString and avoid the cost of string duplication when storing the
563 * string or the member name.
567 * Json::Value aValue( StaticString("some text") );
568 * Json::Value object;
569 * static const StaticString code("code");
570 * object[code] = 1234;
573 class JSON_API StaticString {
575 explicit StaticString(const char* czstring) : c_str_(czstring) {}
577 operator const char*() const { return c_str_; }
579 const char* c_str() const { return c_str_; }
585 /** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
587 * This class is a discriminated union wrapper that can represents a:
588 * - signed integer [range: Value::minInt - Value::maxInt]
589 * - unsigned integer (range: 0 - Value::maxUInt)
594 * - an ordered list of Value
595 * - collection of name/value pairs (javascript object)
597 * The type of the held value is represented by a #ValueType and
598 * can be obtained using type().
600 * Values of an #objectValue or #arrayValue can be accessed using operator[]()
602 * Non-const methods will automatically create the a #nullValue element
603 * if it does not exist.
604 * The sequence of an #arrayValue will be automatically resized and initialized
605 * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
607 * The get() methods can be used to obtain default value in the case the
608 * required element does not exist.
610 * It is possible to iterate over the list of a #objectValue values using
611 * the getMemberNames() method.
613 * \note #Value string-length fit in size_t, but keys must be < 2^30.
614 * (The reason is an implementation detail.) A #CharReader will raise an
615 * exception if a bound is exceeded to avoid security holes in your app,
616 * but the Value API does *not* check bounds. That is the responsibility
619 class JSON_API Value {
620 friend class ValueIteratorBase;
622 typedef std::vector<JSONCPP_STRING> Members;
623 typedef ValueIterator iterator;
624 typedef ValueConstIterator const_iterator;
625 typedef Json::UInt UInt;
626 typedef Json::Int Int;
627 #if defined(JSON_HAS_INT64)
628 typedef Json::UInt64 UInt64;
629 typedef Json::Int64 Int64;
630 #endif // defined(JSON_HAS_INT64)
631 typedef Json::LargestInt LargestInt;
632 typedef Json::LargestUInt LargestUInt;
633 typedef Json::ArrayIndex ArrayIndex;
635 static const Value& null; ///< We regret this reference to a global instance; prefer the simpler Value().
636 static const Value& nullRef; ///< just a kludge for binary-compatibility; same as null
637 static Value const& nullSingleton(); ///< Prefer this to null or nullRef.
639 /// Minimum signed integer value that can be stored in a Json::Value.
640 static const LargestInt minLargestInt;
641 /// Maximum signed integer value that can be stored in a Json::Value.
642 static const LargestInt maxLargestInt;
643 /// Maximum unsigned integer value that can be stored in a Json::Value.
644 static const LargestUInt maxLargestUInt;
646 /// Minimum signed int value that can be stored in a Json::Value.
647 static const Int minInt;
648 /// Maximum signed int value that can be stored in a Json::Value.
649 static const Int maxInt;
650 /// Maximum unsigned int value that can be stored in a Json::Value.
651 static const UInt maxUInt;
653 #if defined(JSON_HAS_INT64)
654 /// Minimum signed 64 bits int value that can be stored in a Json::Value.
655 static const Int64 minInt64;
656 /// Maximum signed 64 bits int value that can be stored in a Json::Value.
657 static const Int64 maxInt64;
658 /// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
659 static const UInt64 maxUInt64;
660 #endif // defined(JSON_HAS_INT64)
663 #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
666 enum DuplicationPolicy {
671 CZString(ArrayIndex index);
672 CZString(char const* str, unsigned length, DuplicationPolicy allocate);
673 CZString(CZString const& other);
674 #if JSON_HAS_RVALUE_REFERENCES
675 CZString(CZString&& other);
678 CZString& operator=(CZString other);
679 bool operator<(CZString const& other) const;
680 bool operator==(CZString const& other) const;
681 ArrayIndex index() const;
682 //const char* c_str() const; ///< \deprecated
683 char const* data() const;
684 unsigned length() const;
685 bool isStaticString() const;
688 void swap(CZString& other);
690 struct StringStorage {
692 unsigned length_: 30; // 1GB max
695 char const* cstr_; // actually, a prefixed string, unless policy is noDup
698 StringStorage storage_;
703 #ifndef JSON_USE_CPPTL_SMALLMAP
704 typedef std::map<CZString, Value> ObjectValues;
706 typedef CppTL::SmallMap<CZString, Value> ObjectValues;
707 #endif // ifndef JSON_USE_CPPTL_SMALLMAP
708 #endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
711 /** \brief Create a default Value of the given type.
713 This is a very useful constructor.
714 To create an empty array, pass arrayValue.
715 To create an empty object, pass objectValue.
716 Another Value can then be set to this one by assignment.
717 This is useful since clear() and resize() will not alter types.
721 Json::Value null_value; // null
722 Json::Value arr_value(Json::arrayValue); // []
723 Json::Value obj_value(Json::objectValue); // {}
726 Value(ValueType type = nullValue);
729 #if defined(JSON_HAS_INT64)
732 #endif // if defined(JSON_HAS_INT64)
734 Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.)
735 Value(const char* begin, const char* end); ///< Copy all, incl zeroes.
736 /** \brief Constructs a value from a static string.
738 * Like other value string constructor but do not duplicate the string for
739 * internal storage. The given string must remain alive after the call to this
741 * \note This works only for null-terminated strings. (We cannot change the
742 * size of this class, so we have nowhere to store the length,
743 * which might be computed later for various operations.)
747 * static StaticString foo("some text");
748 * Json::Value aValue(foo);
751 Value(const StaticString& value);
752 Value(const JSONCPP_STRING& value); ///< Copy data() til size(). Embedded zeroes too.
753 #ifdef JSON_USE_CPPTL
754 Value(const CppTL::ConstString& value);
758 Value(const Value& other);
759 #if JSON_HAS_RVALUE_REFERENCES
761 Value(Value&& other);
765 /// Deep copy, then swap(other).
766 /// \note Over-write existing comments. To preserve comments, use #swapPayload().
767 Value& operator=(Value other);
769 void swap(Value& other);
770 /// Swap values but leave comments and source offsets in place.
771 void swapPayload(Value& other);
773 ValueType type() const;
775 /// Compare payload only, not comments etc.
776 bool operator<(const Value& other) const;
777 bool operator<=(const Value& other) const;
778 bool operator>=(const Value& other) const;
779 bool operator>(const Value& other) const;
780 bool operator==(const Value& other) const;
781 bool operator!=(const Value& other) const;
782 int compare(const Value& other) const;
784 const char* asCString() const; ///< Embedded zeroes could cause you trouble!
785 #if JSONCPP_USING_SECURE_MEMORY
786 unsigned getCStringLength() const; //Allows you to understand the length of the CString
788 JSONCPP_STRING asString() const; ///< Embedded zeroes are possible.
789 /** Get raw char* of string-value.
790 * \return false if !string. (Seg-fault if str or end are NULL.)
793 char const** begin, char const** end) const;
794 #ifdef JSON_USE_CPPTL
795 CppTL::ConstString asConstString() const;
799 #if defined(JSON_HAS_INT64)
800 Int64 asInt64() const;
801 UInt64 asUInt64() const;
802 #endif // if defined(JSON_HAS_INT64)
803 LargestInt asLargestInt() const;
804 LargestUInt asLargestUInt() const;
805 float asFloat() const;
806 double asDouble() const;
812 bool isInt64() const;
814 bool isUInt64() const;
815 bool isIntegral() const;
816 bool isDouble() const;
817 bool isNumeric() const;
818 bool isString() const;
819 bool isArray() const;
820 bool isObject() const;
822 bool isConvertibleTo(ValueType other) const;
824 /// Number of values in array or object
825 ArrayIndex size() const;
827 /// \brief Return true if empty array, empty object, or null;
828 /// otherwise, false.
832 bool operator!() const;
834 /// Remove all object members and array elements.
835 /// \pre type() is arrayValue, objectValue, or nullValue
836 /// \post type() is unchanged
839 /// Resize the array to size elements.
840 /// New elements are initialized to null.
841 /// May only be called on nullValue or arrayValue.
842 /// \pre type() is arrayValue or nullValue
843 /// \post type() is arrayValue
844 void resize(ArrayIndex size);
846 /// Access an array element (zero based index ).
847 /// If the array contains less than index element, then null value are
849 /// in the array so that its size is index+1.
850 /// (You may need to say 'value[0u]' to get your compiler to distinguish
851 /// this from the operator[] which takes a string.)
852 Value& operator[](ArrayIndex index);
854 /// Access an array element (zero based index ).
855 /// If the array contains less than index element, then null value are
857 /// in the array so that its size is index+1.
858 /// (You may need to say 'value[0u]' to get your compiler to distinguish
859 /// this from the operator[] which takes a string.)
860 Value& operator[](int index);
862 /// Access an array element (zero based index )
863 /// (You may need to say 'value[0u]' to get your compiler to distinguish
864 /// this from the operator[] which takes a string.)
865 const Value& operator[](ArrayIndex index) const;
867 /// Access an array element (zero based index )
868 /// (You may need to say 'value[0u]' to get your compiler to distinguish
869 /// this from the operator[] which takes a string.)
870 const Value& operator[](int index) const;
872 /// If the array contains at least index+1 elements, returns the element
874 /// otherwise returns defaultValue.
875 Value get(ArrayIndex index, const Value& defaultValue) const;
876 /// Return true if index < size().
877 bool isValidIndex(ArrayIndex index) const;
878 /// \brief Append value to array at the end.
880 /// Equivalent to jsonvalue[jsonvalue.size()] = value;
881 Value& append(const Value& value);
883 /// Access an object value by name, create a null member if it does not exist.
884 /// \note Because of our implementation, keys are limited to 2^30 -1 chars.
885 /// Exceeding that will cause an exception.
886 Value& operator[](const char* key);
887 /// Access an object value by name, returns null if there is no member with
889 const Value& operator[](const char* key) const;
890 /// Access an object value by name, create a null member if it does not exist.
891 /// \param key may contain embedded nulls.
892 Value& operator[](const JSONCPP_STRING& key);
893 /// Access an object value by name, returns null if there is no member with
895 /// \param key may contain embedded nulls.
896 const Value& operator[](const JSONCPP_STRING& key) const;
897 /** \brief Access an object value by name, create a null member if it does not
900 * If the object has no entry for that name, then the member name used to store
901 * the new entry is not duplicated.
904 * Json::Value object;
905 * static const StaticString code("code");
906 * object[code] = 1234;
909 Value& operator[](const StaticString& key);
910 #ifdef JSON_USE_CPPTL
911 /// Access an object value by name, create a null member if it does not exist.
912 Value& operator[](const CppTL::ConstString& key);
913 /// Access an object value by name, returns null if there is no member with
915 const Value& operator[](const CppTL::ConstString& key) const;
917 /// Return the member named key if it exist, defaultValue otherwise.
919 Value get(const char* key, const Value& defaultValue) const;
920 /// Return the member named key if it exist, defaultValue otherwise.
922 /// \note key may contain embedded nulls.
923 Value get(const char* begin, const char* end, const Value& defaultValue) const;
924 /// Return the member named key if it exist, defaultValue otherwise.
926 /// \param key may contain embedded nulls.
927 Value get(const JSONCPP_STRING& key, const Value& defaultValue) const;
928 #ifdef JSON_USE_CPPTL
929 /// Return the member named key if it exist, defaultValue otherwise.
931 Value get(const CppTL::ConstString& key, const Value& defaultValue) const;
933 /// Most general and efficient version of isMember()const, get()const,
934 /// and operator[]const
935 /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
936 Value const* find(char const* begin, char const* end) const;
937 /// Most general and efficient version of object-mutators.
938 /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
939 /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
940 Value const* demand(char const* begin, char const* end);
941 /// \brief Remove and return the named member.
943 /// Do nothing if it did not exist.
944 /// \return the removed Value, or null.
945 /// \pre type() is objectValue or nullValue
946 /// \post type() is unchanged
948 Value removeMember(const char* key);
949 /// Same as removeMember(const char*)
950 /// \param key may contain embedded nulls.
952 Value removeMember(const JSONCPP_STRING& key);
953 /// Same as removeMember(const char* begin, const char* end, Value* removed),
954 /// but 'key' is null-terminated.
955 bool removeMember(const char* key, Value* removed);
956 /** \brief Remove the named map member.
958 Update 'removed' iff removed.
959 \param key may contain embedded nulls.
960 \return true iff removed (no exceptions)
962 bool removeMember(JSONCPP_STRING const& key, Value* removed);
963 /// Same as removeMember(JSONCPP_STRING const& key, Value* removed)
964 bool removeMember(const char* begin, const char* end, Value* removed);
965 /** \brief Remove the indexed array element.
967 O(n) expensive operations.
968 Update 'removed' iff removed.
969 \return true iff removed (no exceptions)
971 bool removeIndex(ArrayIndex i, Value* removed);
973 /// Return true if the object has a member named key.
974 /// \note 'key' must be null-terminated.
975 bool isMember(const char* key) const;
976 /// Return true if the object has a member named key.
977 /// \param key may contain embedded nulls.
978 bool isMember(const JSONCPP_STRING& key) const;
979 /// Same as isMember(JSONCPP_STRING const& key)const
980 bool isMember(const char* begin, const char* end) const;
981 #ifdef JSON_USE_CPPTL
982 /// Return true if the object has a member named key.
983 bool isMember(const CppTL::ConstString& key) const;
986 /// \brief Return a list of the member names.
988 /// If null, return an empty list.
989 /// \pre type() is objectValue or nullValue
990 /// \post if type() was nullValue, it remains nullValue
991 Members getMemberNames() const;
993 //# ifdef JSON_USE_CPPTL
994 // EnumMemberNames enumMemberNames() const;
995 // EnumValues enumValues() const;
998 /// \deprecated Always pass len.
999 JSONCPP_DEPRECATED("Use setComment(JSONCPP_STRING const&) instead.")
1000 void setComment(const char* comment, CommentPlacement placement);
1001 /// Comments must be //... or /* ... */
1002 void setComment(const char* comment, size_t len, CommentPlacement placement);
1003 /// Comments must be //... or /* ... */
1004 void setComment(const JSONCPP_STRING& comment, CommentPlacement placement);
1005 bool hasComment(CommentPlacement placement) const;
1006 /// Include delimiters and embedded newlines.
1007 JSONCPP_STRING getComment(CommentPlacement placement) const;
1009 JSONCPP_STRING toStyledString() const;
1011 const_iterator begin() const;
1012 const_iterator end() const;
1017 // Accessors for the [start, limit) range of bytes within the JSON text from
1018 // which this value was parsed, if any.
1019 void setOffsetStart(ptrdiff_t start);
1020 void setOffsetLimit(ptrdiff_t limit);
1021 ptrdiff_t getOffsetStart() const;
1022 ptrdiff_t getOffsetLimit() const;
1025 void initBasic(ValueType type, bool allocated = false);
1027 Value& resolveReference(const char* key);
1028 Value& resolveReference(const char* key, const char* end);
1030 struct CommentInfo {
1034 void setComment(const char* text, size_t len);
1039 // struct MemberNamesTransform
1041 // typedef const char *result_type;
1042 // const char *operator()( const CZString &name ) const
1044 // return name.c_str();
1053 char* string_; // actually ptr to unsigned, followed by str, unless !allocated_
1056 ValueType type_ : 8;
1057 unsigned int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
1058 // If not allocated_, string_ must be null-terminated.
1059 CommentInfo* comments_;
1061 // [start, limit) byte offsets in the source JSON text from which this Value
1067 /** \brief Experimental and untested: represents an element of the "path" to
1070 class JSON_API PathArgument {
1075 PathArgument(ArrayIndex index);
1076 PathArgument(const char* key);
1077 PathArgument(const JSONCPP_STRING& key);
1085 JSONCPP_STRING key_;
1090 /** \brief Experimental and untested: represents a "path" to access a node.
1093 * - "." => root node
1094 * - ".[n]" => elements at index 'n' of root node (an array value)
1095 * - ".name" => member named 'name' of root node (an object value)
1096 * - ".name1.name2.name3"
1097 * - ".[0][1][2].name1[3]"
1098 * - ".%" => member name is provided as parameter
1099 * - ".[%]" => index is provied as parameter
1101 class JSON_API Path {
1103 Path(const JSONCPP_STRING& path,
1104 const PathArgument& a1 = PathArgument(),
1105 const PathArgument& a2 = PathArgument(),
1106 const PathArgument& a3 = PathArgument(),
1107 const PathArgument& a4 = PathArgument(),
1108 const PathArgument& a5 = PathArgument());
1110 const Value& resolve(const Value& root) const;
1111 Value resolve(const Value& root, const Value& defaultValue) const;
1112 /// Creates the "path" to access the specified node and returns a reference on
1114 Value& make(Value& root) const;
1117 typedef std::vector<const PathArgument*> InArgs;
1118 typedef std::vector<PathArgument> Args;
1120 void makePath(const JSONCPP_STRING& path, const InArgs& in);
1121 void addPathInArg(const JSONCPP_STRING& path,
1123 InArgs::const_iterator& itInArg,
1124 PathArgument::Kind kind);
1125 void invalidPath(const JSONCPP_STRING& path, int location);
1130 /** \brief base class for Value iterators.
1133 class JSON_API ValueIteratorBase {
1135 typedef std::bidirectional_iterator_tag iterator_category;
1136 typedef unsigned int size_t;
1137 typedef int difference_type;
1138 typedef ValueIteratorBase SelfType;
1140 bool operator==(const SelfType& other) const { return isEqual(other); }
1142 bool operator!=(const SelfType& other) const { return !isEqual(other); }
1144 difference_type operator-(const SelfType& other) const {
1145 return other.computeDistance(*this);
1148 /// Return either the index or the member name of the referenced value as a
1152 /// Return the index of the referenced Value, or -1 if it is not an arrayValue.
1155 /// Return the member name of the referenced Value, or "" if it is not an
1157 /// \note Avoid `c_str()` on result, as embedded zeroes are possible.
1158 JSONCPP_STRING name() const;
1160 /// Return the member name of the referenced Value. "" if it is not an
1162 /// \deprecated This cannot be used for UTF-8 strings, since there can be embedded nulls.
1163 JSONCPP_DEPRECATED("Use `key = name();` instead.")
1164 char const* memberName() const;
1165 /// Return the member name of the referenced Value, or NULL if it is not an
1167 /// \note Better version than memberName(). Allows embedded nulls.
1168 char const* memberName(char const** end) const;
1171 Value& deref() const;
1177 difference_type computeDistance(const SelfType& other) const;
1179 bool isEqual(const SelfType& other) const;
1181 void copy(const SelfType& other);
1184 Value::ObjectValues::iterator current_;
1185 // Indicates that iterator is for a null value.
1189 // For some reason, BORLAND needs these at the end, rather
1190 // than earlier. No idea why.
1191 ValueIteratorBase();
1192 explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
1195 /** \brief const iterator for object and array value.
1198 class JSON_API ValueConstIterator : public ValueIteratorBase {
1202 typedef const Value value_type;
1203 //typedef unsigned int size_t;
1204 //typedef int difference_type;
1205 typedef const Value& reference;
1206 typedef const Value* pointer;
1207 typedef ValueConstIterator SelfType;
1209 ValueConstIterator();
1210 ValueConstIterator(ValueIterator const& other);
1213 /*! \internal Use by Value to create an iterator.
1215 explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
1217 SelfType& operator=(const ValueIteratorBase& other);
1219 SelfType operator++(int) {
1220 SelfType temp(*this);
1225 SelfType operator--(int) {
1226 SelfType temp(*this);
1231 SelfType& operator--() {
1236 SelfType& operator++() {
1241 reference operator*() const { return deref(); }
1243 pointer operator->() const { return &deref(); }
1246 /** \brief Iterator for object and array value.
1248 class JSON_API ValueIterator : public ValueIteratorBase {
1252 typedef Value value_type;
1253 typedef unsigned int size_t;
1254 typedef int difference_type;
1255 typedef Value& reference;
1256 typedef Value* pointer;
1257 typedef ValueIterator SelfType;
1260 explicit ValueIterator(const ValueConstIterator& other);
1261 ValueIterator(const ValueIterator& other);
1264 /*! \internal Use by Value to create an iterator.
1266 explicit ValueIterator(const Value::ObjectValues::iterator& current);
1268 SelfType& operator=(const SelfType& other);
1270 SelfType operator++(int) {
1271 SelfType temp(*this);
1276 SelfType operator--(int) {
1277 SelfType temp(*this);
1282 SelfType& operator--() {
1287 SelfType& operator++() {
1292 reference operator*() const { return deref(); }
1294 pointer operator->() const { return &deref(); }
1301 /// Specialize std::swap() for Json::Value.
1303 inline void swap(Json::Value& a, Json::Value& b) { a.swap(b); }
1308 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1309 #pragma warning(pop)
1310 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1312 #endif // CPPTL_JSON_H_INCLUDED
1314 // //////////////////////////////////////////////////////////////////////
1315 // End of content of file: include/json/value.h
1316 // //////////////////////////////////////////////////////////////////////
1323 // //////////////////////////////////////////////////////////////////////
1324 // Beginning of content of file: include/json/reader.h
1325 // //////////////////////////////////////////////////////////////////////
1327 // Copyright 2007-2010 Baptiste Lepilleur
1328 // Distributed under MIT license, or public domain if desired and
1329 // recognized in your jurisdiction.
1330 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1332 #ifndef CPPTL_JSON_READER_H_INCLUDED
1333 #define CPPTL_JSON_READER_H_INCLUDED
1335 #if !defined(JSON_IS_AMALGAMATION)
1336 #include "features.h"
1338 #endif // if !defined(JSON_IS_AMALGAMATION)
1345 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
1347 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1348 #pragma warning(push)
1349 #pragma warning(disable : 4251)
1350 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1352 #pragma pack(push, 8)
1356 /** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a
1359 * \deprecated Use CharReader and CharReaderBuilder.
1361 class JSON_API Reader {
1364 typedef const Char* Location;
1366 /** \brief An error tagged with where in the JSON text it was encountered.
1368 * The offsets give the [start, limit) range of bytes within the text. Note
1369 * that this is bytes, not codepoints.
1372 struct StructuredError {
1373 ptrdiff_t offset_start;
1374 ptrdiff_t offset_limit;
1375 JSONCPP_STRING message;
1378 /** \brief Constructs a Reader allowing all features
1383 /** \brief Constructs a Reader allowing the specified feature set
1386 Reader(const Features& features);
1388 /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1390 * \param document UTF-8 encoded string containing the document to read.
1391 * \param root [out] Contains the root value of the document if it was
1392 * successfully parsed.
1393 * \param collectComments \c true to collect comment and allow writing them
1395 * serialization, \c false to discard comments.
1396 * This parameter is ignored if
1397 * Features::allowComments_
1399 * \return \c true if the document was successfully parsed, \c false if an
1403 parse(const std::string& document, Value& root, bool collectComments = true);
1405 /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1407 * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
1409 * \param endDoc Pointer on the end of the UTF-8 encoded string of the
1411 * Must be >= beginDoc.
1412 * \param root [out] Contains the root value of the document if it was
1413 * successfully parsed.
1414 * \param collectComments \c true to collect comment and allow writing them
1416 * serialization, \c false to discard comments.
1417 * This parameter is ignored if
1418 Features::allowComments_
1420 * \return \c true if the document was successfully parsed, \c false if an
1423 bool parse(const char* beginDoc,
1426 bool collectComments = true);
1428 /// \brief Parse from input stream.
1429 /// \see Json::operator>>(std::istream&, Json::Value&).
1430 bool parse(JSONCPP_ISTREAM& is, Value& root, bool collectComments = true);
1432 /** \brief Returns a user friendly string that list errors in the parsed
1434 * \return Formatted error message with the list of errors with their location
1436 * the parsed document. An empty string is returned if no error
1439 * \deprecated Use getFormattedErrorMessages() instead (typo fix).
1441 JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.")
1442 JSONCPP_STRING getFormatedErrorMessages() const;
1444 /** \brief Returns a user friendly string that list errors in the parsed
1446 * \return Formatted error message with the list of errors with their location
1448 * the parsed document. An empty string is returned if no error
1452 JSONCPP_STRING getFormattedErrorMessages() const;
1454 /** \brief Returns a vector of structured erros encounted while parsing.
1455 * \return A (possibly empty) vector of StructuredError objects. Currently
1456 * only one error can be returned, but the caller should tolerate
1458 * errors. This can occur if the parser recovers from a non-fatal
1459 * parse error and then encounters additional errors.
1461 std::vector<StructuredError> getStructuredErrors() const;
1463 /** \brief Add a semantic error message.
1464 * \param value JSON Value location associated with the error
1465 * \param message The error message.
1466 * \return \c true if the error was successfully added, \c false if the
1467 * Value offset exceeds the document size.
1469 bool pushError(const Value& value, const JSONCPP_STRING& message);
1471 /** \brief Add a semantic error message with extra context.
1472 * \param value JSON Value location associated with the error
1473 * \param message The error message.
1474 * \param extra Additional JSON Value location to contextualize the error
1475 * \return \c true if the error was successfully added, \c false if either
1476 * Value offset exceeds the document size.
1478 bool pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra);
1480 /** \brief Return whether there are any errors.
1481 * \return \c true if there are no errors to report \c false if
1482 * errors have occurred.
1488 tokenEndOfStream = 0,
1498 tokenArraySeparator,
1499 tokenMemberSeparator,
1514 JSONCPP_STRING message_;
1518 typedef std::deque<ErrorInfo> Errors;
1520 bool readToken(Token& token);
1522 bool match(Location pattern, int patternLength);
1524 bool readCStyleComment();
1525 bool readCppStyleComment();
1529 bool readObject(Token& token);
1530 bool readArray(Token& token);
1531 bool decodeNumber(Token& token);
1532 bool decodeNumber(Token& token, Value& decoded);
1533 bool decodeString(Token& token);
1534 bool decodeString(Token& token, JSONCPP_STRING& decoded);
1535 bool decodeDouble(Token& token);
1536 bool decodeDouble(Token& token, Value& decoded);
1537 bool decodeUnicodeCodePoint(Token& token,
1540 unsigned int& unicode);
1541 bool decodeUnicodeEscapeSequence(Token& token,
1544 unsigned int& unicode);
1545 bool addError(const JSONCPP_STRING& message, Token& token, Location extra = 0);
1546 bool recoverFromError(TokenType skipUntilToken);
1547 bool addErrorAndRecover(const JSONCPP_STRING& message,
1549 TokenType skipUntilToken);
1550 void skipUntilSpace();
1551 Value& currentValue();
1554 getLocationLineAndColumn(Location location, int& line, int& column) const;
1555 JSONCPP_STRING getLocationLineAndColumn(Location location) const;
1556 void addComment(Location begin, Location end, CommentPlacement placement);
1557 void skipCommentTokens(Token& token);
1559 typedef std::stack<Value*> Nodes;
1562 JSONCPP_STRING document_;
1566 Location lastValueEnd_;
1568 JSONCPP_STRING commentsBefore_;
1570 bool collectComments_;
1573 /** Interface for reading JSON from a char array.
1575 class JSON_API CharReader {
1577 virtual ~CharReader() {}
1578 /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1580 * The document must be a UTF-8 encoded string containing the document to read.
1582 * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
1584 * \param endDoc Pointer on the end of the UTF-8 encoded string of the
1586 * Must be >= beginDoc.
1587 * \param root [out] Contains the root value of the document if it was
1588 * successfully parsed.
1589 * \param errs [out] Formatted error messages (if not NULL)
1590 * a user friendly string that lists errors in the parsed
1592 * \return \c true if the document was successfully parsed, \c false if an
1596 char const* beginDoc, char const* endDoc,
1597 Value* root, JSONCPP_STRING* errs) = 0;
1599 class JSON_API Factory {
1601 virtual ~Factory() {}
1602 /** \brief Allocate a CharReader via operator new().
1603 * \throw std::exception if something goes wrong (e.g. invalid settings)
1605 virtual CharReader* newCharReader() const = 0;
1609 /** \brief Build a CharReader implementation.
1613 using namespace Json;
1614 CharReaderBuilder builder;
1615 builder["collectComments"] = false;
1617 JSONCPP_STRING errs;
1618 bool ok = parseFromStream(builder, std::cin, &value, &errs);
1621 class JSON_API CharReaderBuilder : public CharReader::Factory {
1623 // Note: We use a Json::Value so that we can add data-members to this class
1624 // without a major version bump.
1625 /** Configuration of this builder.
1626 These are case-sensitive.
1627 Available settings (case-sensitive):
1628 - `"collectComments": false or true`
1629 - true to collect comment and allow writing them
1630 back during serialization, false to discard comments.
1631 This parameter is ignored if allowComments is false.
1632 - `"allowComments": false or true`
1633 - true if comments are allowed.
1634 - `"strictRoot": false or true`
1635 - true if root must be either an array or an object value
1636 - `"allowDroppedNullPlaceholders": false or true`
1637 - true if dropped null placeholders are allowed. (See StreamWriterBuilder.)
1638 - `"allowNumericKeys": false or true`
1639 - true if numeric object keys are allowed.
1640 - `"allowSingleQuotes": false or true`
1641 - true if '' are allowed for strings (both keys and values)
1642 - `"stackLimit": integer`
1643 - Exceeding stackLimit (recursive depth of `readValue()`) will
1645 - This is a security issue (seg-faults caused by deeply nested JSON),
1646 so the default is low.
1647 - `"failIfExtra": false or true`
1648 - If true, `parse()` returns false when extra non-whitespace trails
1649 the JSON value in the input string.
1650 - `"rejectDupKeys": false or true`
1651 - If true, `parse()` returns false when a key is duplicated within an object.
1652 - `"allowSpecialFloats": false or true`
1653 - If true, special float values (NaNs and infinities) are allowed
1654 and their values are lossfree restorable.
1656 You can examine 'settings_` yourself
1657 to see the defaults. You can also write and read them just like any
1661 Json::Value settings_;
1663 CharReaderBuilder();
1664 ~CharReaderBuilder() JSONCPP_OVERRIDE;
1666 CharReader* newCharReader() const JSONCPP_OVERRIDE;
1668 /** \return true if 'settings' are legal and consistent;
1669 * otherwise, indicate bad settings via 'invalid'.
1671 bool validate(Json::Value* invalid) const;
1673 /** A simple way to update a specific setting.
1675 Value& operator[](JSONCPP_STRING key);
1677 /** Called by ctor, but you can use this to reset settings_.
1678 * \pre 'settings' != NULL (but Json::null is fine)
1680 * \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults
1682 static void setDefaults(Json::Value* settings);
1683 /** Same as old Features::strictMode().
1684 * \pre 'settings' != NULL (but Json::null is fine)
1686 * \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode
1688 static void strictMode(Json::Value* settings);
1691 /** Consume entire stream and use its begin/end.
1692 * Someday we might have a real StreamReader, but for now this
1695 bool JSON_API parseFromStream(
1696 CharReader::Factory const&,
1698 Value* root, std::string* errs);
1700 /** \brief Read from 'sin' into 'root'.
1702 Always keep comments from the input JSON.
1704 This can be used to read a file into a particular sub-object.
1708 cin >> root["dir"]["file"];
1716 // The input stream JSON would be nested here.
1721 \throw std::exception on parse error.
1722 \see Json::operator<<()
1724 JSON_API JSONCPP_ISTREAM& operator>>(JSONCPP_ISTREAM&, Value&);
1730 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1731 #pragma warning(pop)
1732 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1734 #endif // CPPTL_JSON_READER_H_INCLUDED
1736 // //////////////////////////////////////////////////////////////////////
1737 // End of content of file: include/json/reader.h
1738 // //////////////////////////////////////////////////////////////////////
1745 // //////////////////////////////////////////////////////////////////////
1746 // Beginning of content of file: include/json/writer.h
1747 // //////////////////////////////////////////////////////////////////////
1749 // Copyright 2007-2010 Baptiste Lepilleur
1750 // Distributed under MIT license, or public domain if desired and
1751 // recognized in your jurisdiction.
1752 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1754 #ifndef JSON_WRITER_H_INCLUDED
1755 #define JSON_WRITER_H_INCLUDED
1757 #if !defined(JSON_IS_AMALGAMATION)
1759 #endif // if !defined(JSON_IS_AMALGAMATION)
1764 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
1766 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1767 #pragma warning(push)
1768 #pragma warning(disable : 4251)
1769 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1771 #pragma pack(push, 8)
1781 using namespace Json;
1782 void writeToStdout(StreamWriter::Factory const& factory, Value const& value) {
1783 std::unique_ptr<StreamWriter> const writer(
1784 factory.newStreamWriter());
1785 writer->write(value, &std::cout);
1786 std::cout << std::endl; // add lf and flush
1790 class JSON_API StreamWriter {
1792 JSONCPP_OSTREAM* sout_; // not owned; will not delete
1795 virtual ~StreamWriter();
1796 /** Write Value into document as configured in sub-class.
1797 Do not take ownership of sout, but maintain a reference during function.
1799 \return zero on success (For now, we always return zero, so check the stream instead.)
1800 \throw std::exception possibly, depending on configuration
1802 virtual int write(Value const& root, JSONCPP_OSTREAM* sout) = 0;
1804 /** \brief A simple abstract factory.
1806 class JSON_API Factory {
1809 /** \brief Allocate a CharReader via operator new().
1810 * \throw std::exception if something goes wrong (e.g. invalid settings)
1812 virtual StreamWriter* newStreamWriter() const = 0;
1816 /** \brief Write into stringstream, then return string, for convenience.
1817 * A StreamWriter will be created from the factory, used, and then deleted.
1819 JSONCPP_STRING JSON_API writeString(StreamWriter::Factory const& factory, Value const& root);
1822 /** \brief Build a StreamWriter implementation.
1826 using namespace Json;
1828 StreamWriterBuilder builder;
1829 builder["commentStyle"] = "None";
1830 builder["indentation"] = " "; // or whatever you like
1831 std::unique_ptr<Json::StreamWriter> writer(
1832 builder.newStreamWriter());
1833 writer->write(value, &std::cout);
1834 std::cout << std::endl; // add lf and flush
1837 class JSON_API StreamWriterBuilder : public StreamWriter::Factory {
1839 // Note: We use a Json::Value so that we can add data-members to this class
1840 // without a major version bump.
1841 /** Configuration of this builder.
1842 Available settings (case-sensitive):
1843 - "commentStyle": "None" or "All"
1844 - "indentation": "<anything>"
1845 - "enableYAMLCompatibility": false or true
1846 - slightly change the whitespace around colons
1847 - "dropNullPlaceholders": false or true
1848 - Drop the "null" string from the writer's output for nullValues.
1849 Strictly speaking, this is not valid JSON. But when the output is being
1850 fed to a browser's Javascript, it makes for smaller output and the
1851 browser can handle the output just fine.
1852 - "useSpecialFloats": false or true
1853 - If true, outputs non-finite floating point values in the following way:
1854 NaN values as "NaN", positive infinity as "Infinity", and negative infinity
1857 You can examine 'settings_` yourself
1858 to see the defaults. You can also write and read them just like any
1862 Json::Value settings_;
1864 StreamWriterBuilder();
1865 ~StreamWriterBuilder() JSONCPP_OVERRIDE;
1868 * \throw std::exception if something goes wrong (e.g. invalid settings)
1870 StreamWriter* newStreamWriter() const JSONCPP_OVERRIDE;
1872 /** \return true if 'settings' are legal and consistent;
1873 * otherwise, indicate bad settings via 'invalid'.
1875 bool validate(Json::Value* invalid) const;
1876 /** A simple way to update a specific setting.
1878 Value& operator[](JSONCPP_STRING key);
1880 /** Called by ctor, but you can use this to reset settings_.
1881 * \pre 'settings' != NULL (but Json::null is fine)
1883 * \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults
1885 static void setDefaults(Json::Value* settings);
1888 /** \brief Abstract class for writers.
1889 * \deprecated Use StreamWriter. (And really, this is an implementation detail.)
1891 class JSON_API Writer {
1895 virtual JSONCPP_STRING write(const Value& root) = 0;
1898 /** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format
1899 *without formatting (not human friendly).
1901 * The JSON document is written in a single line. It is not intended for 'human'
1903 * but may be usefull to support feature such as RPC where bandwith is limited.
1905 * \deprecated Use StreamWriterBuilder.
1907 class JSON_API FastWriter : public Writer {
1911 ~FastWriter() JSONCPP_OVERRIDE {}
1913 void enableYAMLCompatibility();
1915 /** \brief Drop the "null" string from the writer's output for nullValues.
1916 * Strictly speaking, this is not valid JSON. But when the output is being
1917 * fed to a browser's Javascript, it makes for smaller output and the
1918 * browser can handle the output just fine.
1920 void dropNullPlaceholders();
1922 void omitEndingLineFeed();
1924 public: // overridden from Writer
1925 JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE;
1928 void writeValue(const Value& value);
1930 JSONCPP_STRING document_;
1931 bool yamlCompatiblityEnabled_;
1932 bool dropNullPlaceholders_;
1933 bool omitEndingLineFeed_;
1936 /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
1937 *human friendly way.
1939 * The rules for line break and indent are as follow:
1941 * - if empty then print {} without indent and line break
1942 * - if not empty the print '{', line break & indent, print one value per
1944 * and then unindent and line break and print '}'.
1946 * - if empty then print [] without indent and line break
1947 * - if the array contains no object value, empty array or some other value
1949 * and all the values fit on one lines, then print the array on a single
1951 * - otherwise, it the values do not fit on one line, or the array contains
1952 * object or non empty array, then print one value per line.
1954 * If the Value have comments then they are outputed according to their
1957 * \sa Reader, Value, Value::setComment()
1958 * \deprecated Use StreamWriterBuilder.
1960 class JSON_API StyledWriter : public Writer {
1963 ~StyledWriter() JSONCPP_OVERRIDE {}
1965 public: // overridden from Writer
1966 /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
1967 * \param root Value to serialize.
1968 * \return String containing the JSON document that represents the root value.
1970 JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE;
1973 void writeValue(const Value& value);
1974 void writeArrayValue(const Value& value);
1975 bool isMultineArray(const Value& value);
1976 void pushValue(const JSONCPP_STRING& value);
1978 void writeWithIndent(const JSONCPP_STRING& value);
1981 void writeCommentBeforeValue(const Value& root);
1982 void writeCommentAfterValueOnSameLine(const Value& root);
1983 bool hasCommentForValue(const Value& value);
1984 static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text);
1986 typedef std::vector<JSONCPP_STRING> ChildValues;
1988 ChildValues childValues_;
1989 JSONCPP_STRING document_;
1990 JSONCPP_STRING indentString_;
1991 unsigned int rightMargin_;
1992 unsigned int indentSize_;
1993 bool addChildValues_;
1996 /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
1998 to a stream rather than to a string.
2000 * The rules for line break and indent are as follow:
2002 * - if empty then print {} without indent and line break
2003 * - if not empty the print '{', line break & indent, print one value per
2005 * and then unindent and line break and print '}'.
2007 * - if empty then print [] without indent and line break
2008 * - if the array contains no object value, empty array or some other value
2010 * and all the values fit on one lines, then print the array on a single
2012 * - otherwise, it the values do not fit on one line, or the array contains
2013 * object or non empty array, then print one value per line.
2015 * If the Value have comments then they are outputed according to their
2018 * \param indentation Each level will be indented by this amount extra.
2019 * \sa Reader, Value, Value::setComment()
2020 * \deprecated Use StreamWriterBuilder.
2022 class JSON_API StyledStreamWriter {
2024 StyledStreamWriter(JSONCPP_STRING indentation = "\t");
2025 ~StyledStreamWriter() {}
2028 /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
2029 * \param out Stream to write to. (Can be ostringstream, e.g.)
2030 * \param root Value to serialize.
2031 * \note There is no point in deriving from Writer, since write() should not
2034 void write(JSONCPP_OSTREAM& out, const Value& root);
2037 void writeValue(const Value& value);
2038 void writeArrayValue(const Value& value);
2039 bool isMultineArray(const Value& value);
2040 void pushValue(const JSONCPP_STRING& value);
2042 void writeWithIndent(const JSONCPP_STRING& value);
2045 void writeCommentBeforeValue(const Value& root);
2046 void writeCommentAfterValueOnSameLine(const Value& root);
2047 bool hasCommentForValue(const Value& value);
2048 static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text);
2050 typedef std::vector<JSONCPP_STRING> ChildValues;
2052 ChildValues childValues_;
2053 JSONCPP_OSTREAM* document_;
2054 JSONCPP_STRING indentString_;
2055 unsigned int rightMargin_;
2056 JSONCPP_STRING indentation_;
2057 bool addChildValues_ : 1;
2061 #if defined(JSON_HAS_INT64)
2062 JSONCPP_STRING JSON_API valueToString(Int value);
2063 JSONCPP_STRING JSON_API valueToString(UInt value);
2064 #endif // if defined(JSON_HAS_INT64)
2065 JSONCPP_STRING JSON_API valueToString(LargestInt value);
2066 JSONCPP_STRING JSON_API valueToString(LargestUInt value);
2067 JSONCPP_STRING JSON_API valueToString(double value);
2068 JSONCPP_STRING JSON_API valueToString(bool value);
2069 JSONCPP_STRING JSON_API valueToQuotedString(const char* value);
2071 /// \brief Output using the StyledStreamWriter.
2072 /// \see Json::operator>>()
2073 JSON_API JSONCPP_OSTREAM& operator<<(JSONCPP_OSTREAM&, const Value& root);
2079 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
2080 #pragma warning(pop)
2081 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
2083 #endif // JSON_WRITER_H_INCLUDED
2085 // //////////////////////////////////////////////////////////////////////
2086 // End of content of file: include/json/writer.h
2087 // //////////////////////////////////////////////////////////////////////
2094 // //////////////////////////////////////////////////////////////////////
2095 // Beginning of content of file: include/json/assertions.h
2096 // //////////////////////////////////////////////////////////////////////
2098 // Copyright 2007-2010 Baptiste Lepilleur
2099 // Distributed under MIT license, or public domain if desired and
2100 // recognized in your jurisdiction.
2101 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
2103 #ifndef CPPTL_JSON_ASSERTIONS_H_INCLUDED
2104 #define CPPTL_JSON_ASSERTIONS_H_INCLUDED
2109 #if !defined(JSON_IS_AMALGAMATION)
2111 #endif // if !defined(JSON_IS_AMALGAMATION)
2113 /** It should not be possible for a maliciously designed file to
2114 * cause an abort() or seg-fault, so these macros are used only
2115 * for pre-condition violations and internal logic errors.
2117 #if JSON_USE_EXCEPTION
2119 // @todo <= add detail about condition in exception
2120 # define JSON_ASSERT(condition) \
2121 {if (!(condition)) {Json::throwLogicError( "assert json failed" );}}
2123 # define JSON_FAIL_MESSAGE(message) \
2125 JSONCPP_OSTRINGSTREAM oss; oss << message; \
2126 Json::throwLogicError(oss.str()); \
2130 #else // JSON_USE_EXCEPTION
2132 # define JSON_ASSERT(condition) assert(condition)
2134 // The call to assert() will show the failure message in debug builds. In
2135 // release builds we abort, for a core-dump or debugger.
2136 # define JSON_FAIL_MESSAGE(message) \
2138 JSONCPP_OSTRINGSTREAM oss; oss << message; \
2139 assert(false && oss.str().c_str()); \
2146 #define JSON_ASSERT_MESSAGE(condition, message) \
2147 if (!(condition)) { \
2148 JSON_FAIL_MESSAGE(message); \
2151 #endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED
2153 // //////////////////////////////////////////////////////////////////////
2154 // End of content of file: include/json/assertions.h
2155 // //////////////////////////////////////////////////////////////////////
2161 #endif //ifndef JSON_AMALGATED_H_INCLUDED