1 /// Json-cpp amalgamated 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 Baptiste Lepilleur and The JsonCpp Authors explicitly disclaim 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
19 The JsonCpp Authors, and is 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 and The JsonCpp Authors
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_AMALGAMATED_H_INCLUDED
76 # define JSON_AMALGAMATED_H_INCLUDED
77 /// If defined, indicates that the source file is amalgamated
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.4"
91 # define JSONCPP_VERSION_MAJOR 1
92 # define JSONCPP_VERSION_MINOR 8
93 # define JSONCPP_VERSION_PATCH 4
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 and The JsonCpp Authors
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 amalgamated
147 /// to prevent private header inclusion.
148 /// Remarks: it is automatically defined in the generated amalgamated 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 explicitly 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 # if __has_extension(attribute_deprecated_with_message)
242 # define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
244 #elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
245 # if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
246 # define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
247 # elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
248 # define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__))
249 # endif // GNUC version
250 #endif // __clang__ || __GNUC__
252 #if !defined(JSONCPP_DEPRECATED)
253 #define JSONCPP_DEPRECATED(message)
254 #endif // if !defined(JSONCPP_DEPRECATED)
257 # define JSON_USE_INT64_DOUBLE_CONVERSION 1
260 #if !defined(JSON_IS_AMALGAMATION)
262 # include "version.h"
264 # if JSONCPP_USING_SECURE_MEMORY
265 # include "allocator.h" //typedef Allocator
268 #endif // if !defined(JSON_IS_AMALGAMATION)
272 typedef unsigned int UInt
;
273 #if defined(JSON_NO_INT64)
274 typedef int LargestInt
;
275 typedef unsigned int LargestUInt
;
276 #undef JSON_HAS_INT64
277 #else // if defined(JSON_NO_INT64)
278 // For Microsoft Visual use specific types as long long is not supported
279 #if defined(_MSC_VER) // Microsoft Visual Studio
280 typedef __int64 Int64
;
281 typedef unsigned __int64 UInt64
;
282 #else // if defined(_MSC_VER) // Other platforms, use long long
283 typedef int64_t Int64
;
284 typedef uint64_t UInt64
;
285 #endif // if defined(_MSC_VER)
286 typedef Int64 LargestInt
;
287 typedef UInt64 LargestUInt
;
288 #define JSON_HAS_INT64
289 #endif // if defined(JSON_NO_INT64)
290 #if JSONCPP_USING_SECURE_MEMORY
291 #define JSONCPP_STRING std::basic_string<char, std::char_traits<char>, Json::SecureAllocator<char> >
292 #define JSONCPP_OSTRINGSTREAM std::basic_ostringstream<char, std::char_traits<char>, Json::SecureAllocator<char> >
293 #define JSONCPP_OSTREAM std::basic_ostream<char, std::char_traits<char>>
294 #define JSONCPP_ISTRINGSTREAM std::basic_istringstream<char, std::char_traits<char>, Json::SecureAllocator<char> >
295 #define JSONCPP_ISTREAM std::istream
297 #define JSONCPP_STRING std::string
298 #define JSONCPP_OSTRINGSTREAM std::ostringstream
299 #define JSONCPP_OSTREAM std::ostream
300 #define JSONCPP_ISTRINGSTREAM std::istringstream
301 #define JSONCPP_ISTREAM std::istream
302 #endif // if JSONCPP_USING_SECURE_MEMORY
303 } // end namespace Json
305 #endif // JSON_CONFIG_H_INCLUDED
307 // //////////////////////////////////////////////////////////////////////
308 // End of content of file: include/json/config.h
309 // //////////////////////////////////////////////////////////////////////
316 // //////////////////////////////////////////////////////////////////////
317 // Beginning of content of file: include/json/forwards.h
318 // //////////////////////////////////////////////////////////////////////
320 // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
321 // Distributed under MIT license, or public domain if desired and
322 // recognized in your jurisdiction.
323 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
325 #ifndef JSON_FORWARDS_H_INCLUDED
326 #define JSON_FORWARDS_H_INCLUDED
328 #if !defined(JSON_IS_AMALGAMATION)
330 #endif // if !defined(JSON_IS_AMALGAMATION)
345 typedef unsigned int ArrayIndex
;
350 class ValueIteratorBase
;
352 class ValueConstIterator
;
356 #endif // JSON_FORWARDS_H_INCLUDED
358 // //////////////////////////////////////////////////////////////////////
359 // End of content of file: include/json/forwards.h
360 // //////////////////////////////////////////////////////////////////////
367 // //////////////////////////////////////////////////////////////////////
368 // Beginning of content of file: include/json/features.h
369 // //////////////////////////////////////////////////////////////////////
371 // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
372 // Distributed under MIT license, or public domain if desired and
373 // recognized in your jurisdiction.
374 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
376 #ifndef CPPTL_JSON_FEATURES_H_INCLUDED
377 #define CPPTL_JSON_FEATURES_H_INCLUDED
379 #if !defined(JSON_IS_AMALGAMATION)
380 #include "forwards.h"
381 #endif // if !defined(JSON_IS_AMALGAMATION)
383 #pragma pack(push, 8)
387 /** \brief Configuration passed to reader and writer.
388 * This configuration object can be used to force the Reader or Writer
389 * to behave in a standard conforming way.
391 class JSON_API Features
{
393 /** \brief A configuration that allows all features and assumes all strings
395 * - C & C++ comments are allowed
396 * - Root object can be any JSON value
397 * - Assumes Value strings are encoded in UTF-8
399 static Features
all();
401 /** \brief A configuration that is strictly compatible with the JSON
403 * - Comments are forbidden.
404 * - Root object must be either an array or an object value.
405 * - Assumes Value strings are encoded in UTF-8
407 static Features
strictMode();
409 /** \brief Initialize the configuration like JsonConfig::allFeatures;
413 /// \c true if comments are allowed. Default: \c true.
416 /// \c true if root must be either an array or an object value. Default: \c
420 /// \c true if dropped null placeholders are allowed. Default: \c false.
421 bool allowDroppedNullPlaceholders_
;
423 /// \c true if numeric object key are allowed. Default: \c false.
424 bool allowNumericKeys_
;
431 #endif // CPPTL_JSON_FEATURES_H_INCLUDED
433 // //////////////////////////////////////////////////////////////////////
434 // End of content of file: include/json/features.h
435 // //////////////////////////////////////////////////////////////////////
442 // //////////////////////////////////////////////////////////////////////
443 // Beginning of content of file: include/json/value.h
444 // //////////////////////////////////////////////////////////////////////
446 // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
447 // Distributed under MIT license, or public domain if desired and
448 // recognized in your jurisdiction.
449 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
451 #ifndef CPPTL_JSON_H_INCLUDED
452 #define CPPTL_JSON_H_INCLUDED
454 #if !defined(JSON_IS_AMALGAMATION)
455 #include "forwards.h"
456 #endif // if !defined(JSON_IS_AMALGAMATION)
461 #ifndef JSON_USE_CPPTL_SMALLMAP
464 #include <cpptl/smallmap.h>
466 #ifdef JSON_USE_CPPTL
467 #include <cpptl/forwards.h>
470 //Conditional NORETURN attribute on the throw functions would:
471 // a) suppress false positives from static code analysis
472 // b) possibly improve optimization opportunities.
473 #if !defined(JSONCPP_NORETURN)
474 # if defined(_MSC_VER)
475 # define JSONCPP_NORETURN __declspec(noreturn)
476 # elif defined(__GNUC__)
477 # define JSONCPP_NORETURN __attribute__ ((__noreturn__))
479 # define JSONCPP_NORETURN
483 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
485 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
486 #pragma warning(push)
487 #pragma warning(disable : 4251)
488 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
490 #pragma pack(push, 8)
492 /** \brief JSON (JavaScript Object Notation).
496 /** Base class for all exceptions we throw.
498 * We use nothing but these internally. Of course, STL can throw others.
500 class JSON_API Exception
: public std::exception
{
502 Exception(JSONCPP_STRING
const& msg
);
503 ~Exception() JSONCPP_NOEXCEPT JSONCPP_OVERRIDE
;
504 char const* what() const JSONCPP_NOEXCEPT JSONCPP_OVERRIDE
;
509 /** Exceptions which the user cannot easily avoid.
511 * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
513 * \remark derived from Json::Exception
515 class JSON_API RuntimeError
: public Exception
{
517 RuntimeError(JSONCPP_STRING
const& msg
);
520 /** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
522 * These are precondition-violations (user bugs) and internal errors (our bugs).
524 * \remark derived from Json::Exception
526 class JSON_API LogicError
: public Exception
{
528 LogicError(JSONCPP_STRING
const& msg
);
532 JSONCPP_NORETURN
void throwRuntimeError(JSONCPP_STRING
const& msg
);
534 JSONCPP_NORETURN
void throwLogicError(JSONCPP_STRING
const& msg
);
536 /** \brief Type of the value held by a Value object.
539 nullValue
= 0, ///< 'null' value
540 intValue
, ///< signed integer value
541 uintValue
, ///< unsigned integer value
542 realValue
, ///< double value
543 stringValue
, ///< UTF-8 string value
544 booleanValue
, ///< bool value
545 arrayValue
, ///< array value (ordered list)
546 objectValue
///< object value (collection of name/value pairs).
549 enum CommentPlacement
{
550 commentBefore
= 0, ///< a comment placed on the line before a value
551 commentAfterOnSameLine
, ///< a comment just after a value on the same line
552 commentAfter
, ///< a comment on the line after a value (only make sense for
554 numberOfCommentPlacement
557 //# ifdef JSON_USE_CPPTL
558 // typedef CppTL::AnyEnumerator<const char *> EnumMemberNames;
559 // typedef CppTL::AnyEnumerator<const Value &> EnumValues;
562 /** \brief Lightweight wrapper to tag static string.
564 * Value constructor and objectValue member assignment takes advantage of the
565 * StaticString and avoid the cost of string duplication when storing the
566 * string or the member name.
570 * Json::Value aValue( StaticString("some text") );
571 * Json::Value object;
572 * static const StaticString code("code");
573 * object[code] = 1234;
576 class JSON_API StaticString
{
578 explicit StaticString(const char* czstring
) : c_str_(czstring
) {}
580 operator const char*() const { return c_str_
; }
582 const char* c_str() const { return c_str_
; }
588 /** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
590 * This class is a discriminated union wrapper that can represents a:
591 * - signed integer [range: Value::minInt - Value::maxInt]
592 * - unsigned integer (range: 0 - Value::maxUInt)
597 * - an ordered list of Value
598 * - collection of name/value pairs (javascript object)
600 * The type of the held value is represented by a #ValueType and
601 * can be obtained using type().
603 * Values of an #objectValue or #arrayValue can be accessed using operator[]()
605 * Non-const methods will automatically create the a #nullValue element
606 * if it does not exist.
607 * The sequence of an #arrayValue will be automatically resized and initialized
608 * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
610 * The get() methods can be used to obtain default value in the case the
611 * required element does not exist.
613 * It is possible to iterate over the list of a #objectValue values using
614 * the getMemberNames() method.
616 * \note #Value string-length fit in size_t, but keys must be < 2^30.
617 * (The reason is an implementation detail.) A #CharReader will raise an
618 * exception if a bound is exceeded to avoid security holes in your app,
619 * but the Value API does *not* check bounds. That is the responsibility
622 class JSON_API Value
{
623 friend class ValueIteratorBase
;
625 typedef std::vector
<JSONCPP_STRING
> Members
;
626 typedef ValueIterator iterator
;
627 typedef ValueConstIterator const_iterator
;
628 typedef Json::UInt UInt
;
629 typedef Json::Int Int
;
630 #if defined(JSON_HAS_INT64)
631 typedef Json::UInt64 UInt64
;
632 typedef Json::Int64 Int64
;
633 #endif // defined(JSON_HAS_INT64)
634 typedef Json::LargestInt LargestInt
;
635 typedef Json::LargestUInt LargestUInt
;
636 typedef Json::ArrayIndex ArrayIndex
;
638 // Required for boost integration, e. g. BOOST_TEST
639 typedef std::string value_type
;
641 static const Value
& null
; ///< We regret this reference to a global instance; prefer the simpler Value().
642 static const Value
& nullRef
; ///< just a kludge for binary-compatibility; same as null
643 static Value
const& nullSingleton(); ///< Prefer this to null or nullRef.
645 /// Minimum signed integer value that can be stored in a Json::Value.
646 static const LargestInt minLargestInt
;
647 /// Maximum signed integer value that can be stored in a Json::Value.
648 static const LargestInt maxLargestInt
;
649 /// Maximum unsigned integer value that can be stored in a Json::Value.
650 static const LargestUInt maxLargestUInt
;
652 /// Minimum signed int value that can be stored in a Json::Value.
653 static const Int minInt
;
654 /// Maximum signed int value that can be stored in a Json::Value.
655 static const Int maxInt
;
656 /// Maximum unsigned int value that can be stored in a Json::Value.
657 static const UInt maxUInt
;
659 #if defined(JSON_HAS_INT64)
660 /// Minimum signed 64 bits int value that can be stored in a Json::Value.
661 static const Int64 minInt64
;
662 /// Maximum signed 64 bits int value that can be stored in a Json::Value.
663 static const Int64 maxInt64
;
664 /// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
665 static const UInt64 maxUInt64
;
666 #endif // defined(JSON_HAS_INT64)
669 #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
672 enum DuplicationPolicy
{
677 CZString(ArrayIndex index
);
678 CZString(char const* str
, unsigned length
, DuplicationPolicy allocate
);
679 CZString(CZString
const& other
);
680 #if JSON_HAS_RVALUE_REFERENCES
681 CZString(CZString
&& other
);
684 CZString
& operator=(const CZString
& other
);
686 #if JSON_HAS_RVALUE_REFERENCES
687 CZString
& operator=(CZString
&& other
);
690 bool operator<(CZString
const& other
) const;
691 bool operator==(CZString
const& other
) const;
692 ArrayIndex
index() const;
693 //const char* c_str() const; ///< \deprecated
694 char const* data() const;
695 unsigned length() const;
696 bool isStaticString() const;
699 void swap(CZString
& other
);
701 struct StringStorage
{
703 unsigned length_
: 30; // 1GB max
706 char const* cstr_
; // actually, a prefixed string, unless policy is noDup
709 StringStorage storage_
;
714 #ifndef JSON_USE_CPPTL_SMALLMAP
715 typedef std::map
<CZString
, Value
> ObjectValues
;
717 typedef CppTL::SmallMap
<CZString
, Value
> ObjectValues
;
718 #endif // ifndef JSON_USE_CPPTL_SMALLMAP
719 #endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
722 /** \brief Create a default Value of the given type.
724 This is a very useful constructor.
725 To create an empty array, pass arrayValue.
726 To create an empty object, pass objectValue.
727 Another Value can then be set to this one by assignment.
728 This is useful since clear() and resize() will not alter types.
732 Json::Value null_value; // null
733 Json::Value arr_value(Json::arrayValue); // []
734 Json::Value obj_value(Json::objectValue); // {}
737 Value(ValueType type
= nullValue
);
740 #if defined(JSON_HAS_INT64)
743 #endif // if defined(JSON_HAS_INT64)
745 Value(const char* value
); ///< Copy til first 0. (NULL causes to seg-fault.)
746 Value(const char* begin
, const char* end
); ///< Copy all, incl zeroes.
747 /** \brief Constructs a value from a static string.
749 * Like other value string constructor but do not duplicate the string for
750 * internal storage. The given string must remain alive after the call to this
752 * \note This works only for null-terminated strings. (We cannot change the
753 * size of this class, so we have nowhere to store the length,
754 * which might be computed later for various operations.)
758 * static StaticString foo("some text");
759 * Json::Value aValue(foo);
762 Value(const StaticString
& value
);
763 Value(const JSONCPP_STRING
& value
); ///< Copy data() til size(). Embedded zeroes too.
764 #ifdef JSON_USE_CPPTL
765 Value(const CppTL::ConstString
& value
);
769 Value(const Value
& other
);
770 #if JSON_HAS_RVALUE_REFERENCES
772 Value(Value
&& other
);
776 /// Deep copy, then swap(other).
777 /// \note Over-write existing comments. To preserve comments, use #swapPayload().
778 Value
& operator=(Value other
);
781 void swap(Value
& other
);
782 /// Swap values but leave comments and source offsets in place.
783 void swapPayload(Value
& other
);
786 void copy(const Value
& other
);
787 /// copy values but leave comments and source offsets in place.
788 void copyPayload(const Value
& other
);
790 ValueType
type() const;
792 /// Compare payload only, not comments etc.
793 bool operator<(const Value
& other
) const;
794 bool operator<=(const Value
& other
) const;
795 bool operator>=(const Value
& other
) const;
796 bool operator>(const Value
& other
) const;
797 bool operator==(const Value
& other
) const;
798 bool operator!=(const Value
& other
) const;
799 int compare(const Value
& other
) const;
801 const char* asCString() const; ///< Embedded zeroes could cause you trouble!
802 #if JSONCPP_USING_SECURE_MEMORY
803 unsigned getCStringLength() const; //Allows you to understand the length of the CString
805 JSONCPP_STRING
asString() const; ///< Embedded zeroes are possible.
806 /** Get raw char* of string-value.
807 * \return false if !string. (Seg-fault if str or end are NULL.)
810 char const** begin
, char const** end
) const;
811 #ifdef JSON_USE_CPPTL
812 CppTL::ConstString
asConstString() const;
816 #if defined(JSON_HAS_INT64)
817 Int64
asInt64() const;
818 UInt64
asUInt64() const;
819 #endif // if defined(JSON_HAS_INT64)
820 LargestInt
asLargestInt() const;
821 LargestUInt
asLargestUInt() const;
822 float asFloat() const;
823 double asDouble() const;
829 bool isInt64() const;
831 bool isUInt64() const;
832 bool isIntegral() const;
833 bool isDouble() const;
834 bool isNumeric() const;
835 bool isString() const;
836 bool isArray() const;
837 bool isObject() const;
839 bool isConvertibleTo(ValueType other
) const;
841 /// Number of values in array or object
842 ArrayIndex
size() const;
844 /// \brief Return true if empty array, empty object, or null;
845 /// otherwise, false.
849 explicit operator bool() const;
851 /// Remove all object members and array elements.
852 /// \pre type() is arrayValue, objectValue, or nullValue
853 /// \post type() is unchanged
856 /// Resize the array to size elements.
857 /// New elements are initialized to null.
858 /// May only be called on nullValue or arrayValue.
859 /// \pre type() is arrayValue or nullValue
860 /// \post type() is arrayValue
861 void resize(ArrayIndex size
);
863 /// Access an array element (zero based index ).
864 /// If the array contains less than index element, then null value are
866 /// in the array so that its size is index+1.
867 /// (You may need to say 'value[0u]' to get your compiler to distinguish
868 /// this from the operator[] which takes a string.)
869 Value
& operator[](ArrayIndex index
);
871 /// Access an array element (zero based index ).
872 /// If the array contains less than index element, then null value are
874 /// in the array so that its size is index+1.
875 /// (You may need to say 'value[0u]' to get your compiler to distinguish
876 /// this from the operator[] which takes a string.)
877 Value
& operator[](int index
);
879 /// Access an array element (zero based index )
880 /// (You may need to say 'value[0u]' to get your compiler to distinguish
881 /// this from the operator[] which takes a string.)
882 const Value
& operator[](ArrayIndex index
) const;
884 /// Access an array element (zero based index )
885 /// (You may need to say 'value[0u]' to get your compiler to distinguish
886 /// this from the operator[] which takes a string.)
887 const Value
& operator[](int index
) const;
889 /// If the array contains at least index+1 elements, returns the element
891 /// otherwise returns defaultValue.
892 Value
get(ArrayIndex index
, const Value
& defaultValue
) const;
893 /// Return true if index < size().
894 bool isValidIndex(ArrayIndex index
) const;
895 /// \brief Append value to array at the end.
897 /// Equivalent to jsonvalue[jsonvalue.size()] = value;
898 Value
& append(const Value
& value
);
900 #if JSON_HAS_RVALUE_REFERENCES
901 Value
& append(Value
&& value
);
904 /// Access an object value by name, create a null member if it does not exist.
905 /// \note Because of our implementation, keys are limited to 2^30 -1 chars.
906 /// Exceeding that will cause an exception.
907 Value
& operator[](const char* key
);
908 /// Access an object value by name, returns null if there is no member with
910 const Value
& operator[](const char* key
) const;
911 /// Access an object value by name, create a null member if it does not exist.
912 /// \param key may contain embedded nulls.
913 Value
& operator[](const JSONCPP_STRING
& key
);
914 /// Access an object value by name, returns null if there is no member with
916 /// \param key may contain embedded nulls.
917 const Value
& operator[](const JSONCPP_STRING
& key
) const;
918 /** \brief Access an object value by name, create a null member if it does not
921 * If the object has no entry for that name, then the member name used to store
922 * the new entry is not duplicated.
925 * Json::Value object;
926 * static const StaticString code("code");
927 * object[code] = 1234;
930 Value
& operator[](const StaticString
& key
);
931 #ifdef JSON_USE_CPPTL
932 /// Access an object value by name, create a null member if it does not exist.
933 Value
& operator[](const CppTL::ConstString
& key
);
934 /// Access an object value by name, returns null if there is no member with
936 const Value
& operator[](const CppTL::ConstString
& key
) const;
938 /// Return the member named key if it exist, defaultValue otherwise.
940 Value
get(const char* key
, const Value
& defaultValue
) const;
941 /// Return the member named key if it exist, defaultValue otherwise.
943 /// \note key may contain embedded nulls.
944 Value
get(const char* begin
, const char* end
, const Value
& defaultValue
) const;
945 /// Return the member named key if it exist, defaultValue otherwise.
947 /// \param key may contain embedded nulls.
948 Value
get(const JSONCPP_STRING
& key
, const Value
& defaultValue
) const;
949 #ifdef JSON_USE_CPPTL
950 /// Return the member named key if it exist, defaultValue otherwise.
952 Value
get(const CppTL::ConstString
& key
, const Value
& defaultValue
) const;
954 /// Most general and efficient version of isMember()const, get()const,
955 /// and operator[]const
956 /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
957 Value
const* find(char const* begin
, char const* end
) const;
958 /// Most general and efficient version of object-mutators.
959 /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
960 /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
961 Value
const* demand(char const* begin
, char const* end
);
962 /// \brief Remove and return the named member.
964 /// Do nothing if it did not exist.
965 /// \return the removed Value, or null.
966 /// \pre type() is objectValue or nullValue
967 /// \post type() is unchanged
969 void removeMember(const char* key
);
970 /// Same as removeMember(const char*)
971 /// \param key may contain embedded nulls.
973 void removeMember(const JSONCPP_STRING
& key
);
974 /// Same as removeMember(const char* begin, const char* end, Value* removed),
975 /// but 'key' is null-terminated.
976 bool removeMember(const char* key
, Value
* removed
);
977 /** \brief Remove the named map member.
979 Update 'removed' iff removed.
980 \param key may contain embedded nulls.
981 \return true iff removed (no exceptions)
983 bool removeMember(JSONCPP_STRING
const& key
, Value
* removed
);
984 /// Same as removeMember(JSONCPP_STRING const& key, Value* removed)
985 bool removeMember(const char* begin
, const char* end
, Value
* removed
);
986 /** \brief Remove the indexed array element.
988 O(n) expensive operations.
989 Update 'removed' iff removed.
990 \return true iff removed (no exceptions)
992 bool removeIndex(ArrayIndex i
, Value
* removed
);
994 /// Return true if the object has a member named key.
995 /// \note 'key' must be null-terminated.
996 bool isMember(const char* key
) const;
997 /// Return true if the object has a member named key.
998 /// \param key may contain embedded nulls.
999 bool isMember(const JSONCPP_STRING
& key
) const;
1000 /// Same as isMember(JSONCPP_STRING const& key)const
1001 bool isMember(const char* begin
, const char* end
) const;
1002 #ifdef JSON_USE_CPPTL
1003 /// Return true if the object has a member named key.
1004 bool isMember(const CppTL::ConstString
& key
) const;
1007 /// \brief Return a list of the member names.
1009 /// If null, return an empty list.
1010 /// \pre type() is objectValue or nullValue
1011 /// \post if type() was nullValue, it remains nullValue
1012 Members
getMemberNames() const;
1014 //# ifdef JSON_USE_CPPTL
1015 // EnumMemberNames enumMemberNames() const;
1016 // EnumValues enumValues() const;
1019 /// \deprecated Always pass len.
1020 JSONCPP_DEPRECATED("Use setComment(JSONCPP_STRING const&) instead.")
1021 void setComment(const char* comment
, CommentPlacement placement
);
1022 /// Comments must be //... or /* ... */
1023 void setComment(const char* comment
, size_t len
, CommentPlacement placement
);
1024 /// Comments must be //... or /* ... */
1025 void setComment(const JSONCPP_STRING
& comment
, CommentPlacement placement
);
1026 bool hasComment(CommentPlacement placement
) const;
1027 /// Include delimiters and embedded newlines.
1028 JSONCPP_STRING
getComment(CommentPlacement placement
) const;
1030 JSONCPP_STRING
toStyledString() const;
1032 const_iterator
begin() const;
1033 const_iterator
end() const;
1038 // Accessors for the [start, limit) range of bytes within the JSON text from
1039 // which this value was parsed, if any.
1040 void setOffsetStart(ptrdiff_t start
);
1041 void setOffsetLimit(ptrdiff_t limit
);
1042 ptrdiff_t getOffsetStart() const;
1043 ptrdiff_t getOffsetLimit() const;
1046 void initBasic(ValueType type
, bool allocated
= false);
1048 Value
& resolveReference(const char* key
);
1049 Value
& resolveReference(const char* key
, const char* end
);
1051 struct CommentInfo
{
1055 void setComment(const char* text
, size_t len
);
1060 // struct MemberNamesTransform
1062 // typedef const char *result_type;
1063 // const char *operator()( const CZString &name ) const
1065 // return name.c_str();
1074 char* string_
; // actually ptr to unsigned, followed by str, unless !allocated_
1077 ValueType type_
: 8;
1078 unsigned int allocated_
: 1; // Notes: if declared as bool, bitfield is useless.
1079 // If not allocated_, string_ must be null-terminated.
1080 CommentInfo
* comments_
;
1082 // [start, limit) byte offsets in the source JSON text from which this Value
1088 /** \brief Experimental and untested: represents an element of the "path" to
1091 class JSON_API PathArgument
{
1096 PathArgument(ArrayIndex index
);
1097 PathArgument(const char* key
);
1098 PathArgument(const JSONCPP_STRING
& key
);
1106 JSONCPP_STRING key_
;
1111 /** \brief Experimental and untested: represents a "path" to access a node.
1114 * - "." => root node
1115 * - ".[n]" => elements at index 'n' of root node (an array value)
1116 * - ".name" => member named 'name' of root node (an object value)
1117 * - ".name1.name2.name3"
1118 * - ".[0][1][2].name1[3]"
1119 * - ".%" => member name is provided as parameter
1120 * - ".[%]" => index is provied as parameter
1122 class JSON_API Path
{
1124 Path(const JSONCPP_STRING
& path
,
1125 const PathArgument
& a1
= PathArgument(),
1126 const PathArgument
& a2
= PathArgument(),
1127 const PathArgument
& a3
= PathArgument(),
1128 const PathArgument
& a4
= PathArgument(),
1129 const PathArgument
& a5
= PathArgument());
1131 const Value
& resolve(const Value
& root
) const;
1132 Value
resolve(const Value
& root
, const Value
& defaultValue
) const;
1133 /// Creates the "path" to access the specified node and returns a reference on
1135 Value
& make(Value
& root
) const;
1138 typedef std::vector
<const PathArgument
*> InArgs
;
1139 typedef std::vector
<PathArgument
> Args
;
1141 void makePath(const JSONCPP_STRING
& path
, const InArgs
& in
);
1142 void addPathInArg(const JSONCPP_STRING
& path
,
1144 InArgs::const_iterator
& itInArg
,
1145 PathArgument::Kind kind
);
1146 void invalidPath(const JSONCPP_STRING
& path
, int location
);
1151 /** \brief base class for Value iterators.
1154 class JSON_API ValueIteratorBase
{
1156 typedef std::bidirectional_iterator_tag iterator_category
;
1157 typedef unsigned int size_t;
1158 typedef int difference_type
;
1159 typedef ValueIteratorBase SelfType
;
1161 bool operator==(const SelfType
& other
) const { return isEqual(other
); }
1163 bool operator!=(const SelfType
& other
) const { return !isEqual(other
); }
1165 difference_type
operator-(const SelfType
& other
) const {
1166 return other
.computeDistance(*this);
1169 /// Return either the index or the member name of the referenced value as a
1173 /// Return the index of the referenced Value, or -1 if it is not an arrayValue.
1176 /// Return the member name of the referenced Value, or "" if it is not an
1178 /// \note Avoid `c_str()` on result, as embedded zeroes are possible.
1179 JSONCPP_STRING
name() const;
1181 /// Return the member name of the referenced Value. "" if it is not an
1183 /// \deprecated This cannot be used for UTF-8 strings, since there can be embedded nulls.
1184 JSONCPP_DEPRECATED("Use `key = name();` instead.")
1185 char const* memberName() const;
1186 /// Return the member name of the referenced Value, or NULL if it is not an
1188 /// \note Better version than memberName(). Allows embedded nulls.
1189 char const* memberName(char const** end
) const;
1192 Value
& deref() const;
1198 difference_type
computeDistance(const SelfType
& other
) const;
1200 bool isEqual(const SelfType
& other
) const;
1202 void copy(const SelfType
& other
);
1205 Value::ObjectValues::iterator current_
;
1206 // Indicates that iterator is for a null value.
1210 // For some reason, BORLAND needs these at the end, rather
1211 // than earlier. No idea why.
1212 ValueIteratorBase();
1213 explicit ValueIteratorBase(const Value::ObjectValues::iterator
& current
);
1216 /** \brief const iterator for object and array value.
1219 class JSON_API ValueConstIterator
: public ValueIteratorBase
{
1223 typedef const Value value_type
;
1224 //typedef unsigned int size_t;
1225 //typedef int difference_type;
1226 typedef const Value
& reference
;
1227 typedef const Value
* pointer
;
1228 typedef ValueConstIterator SelfType
;
1230 ValueConstIterator();
1231 ValueConstIterator(ValueIterator
const& other
);
1234 /*! \internal Use by Value to create an iterator.
1236 explicit ValueConstIterator(const Value::ObjectValues::iterator
& current
);
1238 SelfType
& operator=(const ValueIteratorBase
& other
);
1240 SelfType
operator++(int) {
1241 SelfType
temp(*this);
1246 SelfType
operator--(int) {
1247 SelfType
temp(*this);
1252 SelfType
& operator--() {
1257 SelfType
& operator++() {
1262 reference
operator*() const { return deref(); }
1264 pointer
operator->() const { return &deref(); }
1267 /** \brief Iterator for object and array value.
1269 class JSON_API ValueIterator
: public ValueIteratorBase
{
1273 typedef Value value_type
;
1274 typedef unsigned int size_t;
1275 typedef int difference_type
;
1276 typedef Value
& reference
;
1277 typedef Value
* pointer
;
1278 typedef ValueIterator SelfType
;
1281 explicit ValueIterator(const ValueConstIterator
& other
);
1282 ValueIterator(const ValueIterator
& other
);
1285 /*! \internal Use by Value to create an iterator.
1287 explicit ValueIterator(const Value::ObjectValues::iterator
& current
);
1289 SelfType
& operator=(const SelfType
& other
);
1291 SelfType
operator++(int) {
1292 SelfType
temp(*this);
1297 SelfType
operator--(int) {
1298 SelfType
temp(*this);
1303 SelfType
& operator--() {
1308 SelfType
& operator++() {
1313 reference
operator*() const { return deref(); }
1315 pointer
operator->() const { return &deref(); }
1322 /// Specialize std::swap() for Json::Value.
1324 inline void swap(Json::Value
& a
, Json::Value
& b
) { a
.swap(b
); }
1329 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1330 #pragma warning(pop)
1331 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1333 #endif // CPPTL_JSON_H_INCLUDED
1335 // //////////////////////////////////////////////////////////////////////
1336 // End of content of file: include/json/value.h
1337 // //////////////////////////////////////////////////////////////////////
1344 // //////////////////////////////////////////////////////////////////////
1345 // Beginning of content of file: include/json/reader.h
1346 // //////////////////////////////////////////////////////////////////////
1348 // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
1349 // Distributed under MIT license, or public domain if desired and
1350 // recognized in your jurisdiction.
1351 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1353 #ifndef CPPTL_JSON_READER_H_INCLUDED
1354 #define CPPTL_JSON_READER_H_INCLUDED
1356 #if !defined(JSON_IS_AMALGAMATION)
1357 #include "features.h"
1359 #endif // if !defined(JSON_IS_AMALGAMATION)
1366 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
1368 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1369 #pragma warning(push)
1370 #pragma warning(disable : 4251)
1371 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1373 #pragma pack(push, 8)
1377 /** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a
1380 * \deprecated Use CharReader and CharReaderBuilder.
1382 class JSONCPP_DEPRECATED("Use CharReader and CharReaderBuilder instead") JSON_API Reader
{
1385 typedef const Char
* Location
;
1387 /** \brief An error tagged with where in the JSON text it was encountered.
1389 * The offsets give the [start, limit) range of bytes within the text. Note
1390 * that this is bytes, not codepoints.
1393 struct StructuredError
{
1394 ptrdiff_t offset_start
;
1395 ptrdiff_t offset_limit
;
1396 JSONCPP_STRING message
;
1399 /** \brief Constructs a Reader allowing all features
1404 /** \brief Constructs a Reader allowing the specified feature set
1407 Reader(const Features
& features
);
1409 /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1411 * \param document UTF-8 encoded string containing the document to read.
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
1424 parse(const std::string
& document
, Value
& root
, bool collectComments
= true);
1426 /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1428 * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
1430 * \param endDoc Pointer on the end of the UTF-8 encoded string of the
1432 * Must be >= beginDoc.
1433 * \param root [out] Contains the root value of the document if it was
1434 * successfully parsed.
1435 * \param collectComments \c true to collect comment and allow writing them
1437 * serialization, \c false to discard comments.
1438 * This parameter is ignored if
1439 Features::allowComments_
1441 * \return \c true if the document was successfully parsed, \c false if an
1444 bool parse(const char* beginDoc
,
1447 bool collectComments
= true);
1449 /// \brief Parse from input stream.
1450 /// \see Json::operator>>(std::istream&, Json::Value&).
1451 bool parse(JSONCPP_ISTREAM
& is
, Value
& root
, bool collectComments
= true);
1453 /** \brief Returns a user friendly string that list errors in the parsed
1455 * \return Formatted error message with the list of errors with their location
1457 * the parsed document. An empty string is returned if no error
1460 * \deprecated Use getFormattedErrorMessages() instead (typo fix).
1462 JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.")
1463 JSONCPP_STRING
getFormatedErrorMessages() const;
1465 /** \brief Returns a user friendly string that list errors in the parsed
1467 * \return Formatted error message with the list of errors with their location
1469 * the parsed document. An empty string is returned if no error
1473 JSONCPP_STRING
getFormattedErrorMessages() const;
1475 /** \brief Returns a vector of structured erros encounted while parsing.
1476 * \return A (possibly empty) vector of StructuredError objects. Currently
1477 * only one error can be returned, but the caller should tolerate
1479 * errors. This can occur if the parser recovers from a non-fatal
1480 * parse error and then encounters additional errors.
1482 std::vector
<StructuredError
> getStructuredErrors() const;
1484 /** \brief Add a semantic error message.
1485 * \param value JSON Value location associated with the error
1486 * \param message The error message.
1487 * \return \c true if the error was successfully added, \c false if the
1488 * Value offset exceeds the document size.
1490 bool pushError(const Value
& value
, const JSONCPP_STRING
& message
);
1492 /** \brief Add a semantic error message with extra context.
1493 * \param value JSON Value location associated with the error
1494 * \param message The error message.
1495 * \param extra Additional JSON Value location to contextualize the error
1496 * \return \c true if the error was successfully added, \c false if either
1497 * Value offset exceeds the document size.
1499 bool pushError(const Value
& value
, const JSONCPP_STRING
& message
, const Value
& extra
);
1501 /** \brief Return whether there are any errors.
1502 * \return \c true if there are no errors to report \c false if
1503 * errors have occurred.
1509 tokenEndOfStream
= 0,
1519 tokenArraySeparator
,
1520 tokenMemberSeparator
,
1535 JSONCPP_STRING message_
;
1539 typedef std::deque
<ErrorInfo
> Errors
;
1541 bool readToken(Token
& token
);
1543 bool match(Location pattern
, int patternLength
);
1545 bool readCStyleComment();
1546 bool readCppStyleComment();
1550 bool readObject(Token
& token
);
1551 bool readArray(Token
& token
);
1552 bool decodeNumber(Token
& token
);
1553 bool decodeNumber(Token
& token
, Value
& decoded
);
1554 bool decodeString(Token
& token
);
1555 bool decodeString(Token
& token
, JSONCPP_STRING
& decoded
);
1556 bool decodeDouble(Token
& token
);
1557 bool decodeDouble(Token
& token
, Value
& decoded
);
1558 bool decodeUnicodeCodePoint(Token
& token
,
1561 unsigned int& unicode
);
1562 bool decodeUnicodeEscapeSequence(Token
& token
,
1565 unsigned int& unicode
);
1566 bool addError(const JSONCPP_STRING
& message
, Token
& token
, Location extra
= 0);
1567 bool recoverFromError(TokenType skipUntilToken
);
1568 bool addErrorAndRecover(const JSONCPP_STRING
& message
,
1570 TokenType skipUntilToken
);
1571 void skipUntilSpace();
1572 Value
& currentValue();
1575 getLocationLineAndColumn(Location location
, int& line
, int& column
) const;
1576 JSONCPP_STRING
getLocationLineAndColumn(Location location
) const;
1577 void addComment(Location begin
, Location end
, CommentPlacement placement
);
1578 void skipCommentTokens(Token
& token
);
1580 static bool containsNewLine(Location begin
, Location end
);
1581 static JSONCPP_STRING
normalizeEOL(Location begin
, Location end
);
1583 typedef std::stack
<Value
*> Nodes
;
1586 JSONCPP_STRING document_
;
1590 Location lastValueEnd_
;
1592 JSONCPP_STRING commentsBefore_
;
1594 bool collectComments_
;
1597 /** Interface for reading JSON from a char array.
1599 class JSON_API CharReader
{
1601 virtual ~CharReader() {}
1602 /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1604 * The document must be a UTF-8 encoded string containing the document to read.
1606 * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
1608 * \param endDoc Pointer on the end of the UTF-8 encoded string of the
1610 * Must be >= beginDoc.
1611 * \param root [out] Contains the root value of the document if it was
1612 * successfully parsed.
1613 * \param errs [out] Formatted error messages (if not NULL)
1614 * a user friendly string that lists errors in the parsed
1616 * \return \c true if the document was successfully parsed, \c false if an
1620 char const* beginDoc
, char const* endDoc
,
1621 Value
* root
, JSONCPP_STRING
* errs
) = 0;
1623 class JSON_API Factory
{
1625 virtual ~Factory() {}
1626 /** \brief Allocate a CharReader via operator new().
1627 * \throw std::exception if something goes wrong (e.g. invalid settings)
1629 virtual CharReader
* newCharReader() const = 0;
1633 /** \brief Build a CharReader implementation.
1637 using namespace Json;
1638 CharReaderBuilder builder;
1639 builder["collectComments"] = false;
1641 JSONCPP_STRING errs;
1642 bool ok = parseFromStream(builder, std::cin, &value, &errs);
1645 class JSON_API CharReaderBuilder
: public CharReader::Factory
{
1647 // Note: We use a Json::Value so that we can add data-members to this class
1648 // without a major version bump.
1649 /** Configuration of this builder.
1650 These are case-sensitive.
1651 Available settings (case-sensitive):
1652 - `"collectComments": false or true`
1653 - true to collect comment and allow writing them
1654 back during serialization, false to discard comments.
1655 This parameter is ignored if allowComments is false.
1656 - `"allowComments": false or true`
1657 - true if comments are allowed.
1658 - `"strictRoot": false or true`
1659 - true if root must be either an array or an object value
1660 - `"allowDroppedNullPlaceholders": false or true`
1661 - true if dropped null placeholders are allowed. (See StreamWriterBuilder.)
1662 - `"allowNumericKeys": false or true`
1663 - true if numeric object keys are allowed.
1664 - `"allowSingleQuotes": false or true`
1665 - true if '' are allowed for strings (both keys and values)
1666 - `"stackLimit": integer`
1667 - Exceeding stackLimit (recursive depth of `readValue()`) will
1669 - This is a security issue (seg-faults caused by deeply nested JSON),
1670 so the default is low.
1671 - `"failIfExtra": false or true`
1672 - If true, `parse()` returns false when extra non-whitespace trails
1673 the JSON value in the input string.
1674 - `"rejectDupKeys": false or true`
1675 - If true, `parse()` returns false when a key is duplicated within an object.
1676 - `"allowSpecialFloats": false or true`
1677 - If true, special float values (NaNs and infinities) are allowed
1678 and their values are lossfree restorable.
1680 You can examine 'settings_` yourself
1681 to see the defaults. You can also write and read them just like any
1685 Json::Value settings_
;
1687 CharReaderBuilder();
1688 ~CharReaderBuilder() JSONCPP_OVERRIDE
;
1690 CharReader
* newCharReader() const JSONCPP_OVERRIDE
;
1692 /** \return true if 'settings' are legal and consistent;
1693 * otherwise, indicate bad settings via 'invalid'.
1695 bool validate(Json::Value
* invalid
) const;
1697 /** A simple way to update a specific setting.
1699 Value
& operator[](JSONCPP_STRING key
);
1701 /** Called by ctor, but you can use this to reset settings_.
1702 * \pre 'settings' != NULL (but Json::null is fine)
1704 * \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults
1706 static void setDefaults(Json::Value
* settings
);
1707 /** Same as old Features::strictMode().
1708 * \pre 'settings' != NULL (but Json::null is fine)
1710 * \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode
1712 static void strictMode(Json::Value
* settings
);
1715 /** Consume entire stream and use its begin/end.
1716 * Someday we might have a real StreamReader, but for now this
1719 bool JSON_API
parseFromStream(
1720 CharReader::Factory
const&,
1722 Value
* root
, std::string
* errs
);
1724 /** \brief Read from 'sin' into 'root'.
1726 Always keep comments from the input JSON.
1728 This can be used to read a file into a particular sub-object.
1732 cin >> root["dir"]["file"];
1740 // The input stream JSON would be nested here.
1745 \throw std::exception on parse error.
1746 \see Json::operator<<()
1748 JSON_API JSONCPP_ISTREAM
& operator>>(JSONCPP_ISTREAM
&, Value
&);
1754 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1755 #pragma warning(pop)
1756 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1758 #endif // CPPTL_JSON_READER_H_INCLUDED
1760 // //////////////////////////////////////////////////////////////////////
1761 // End of content of file: include/json/reader.h
1762 // //////////////////////////////////////////////////////////////////////
1769 // //////////////////////////////////////////////////////////////////////
1770 // Beginning of content of file: include/json/writer.h
1771 // //////////////////////////////////////////////////////////////////////
1773 // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
1774 // Distributed under MIT license, or public domain if desired and
1775 // recognized in your jurisdiction.
1776 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1778 #ifndef JSON_WRITER_H_INCLUDED
1779 #define JSON_WRITER_H_INCLUDED
1781 #if !defined(JSON_IS_AMALGAMATION)
1783 #endif // if !defined(JSON_IS_AMALGAMATION)
1788 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
1790 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) && defined(_MSC_VER)
1791 #pragma warning(push)
1792 #pragma warning(disable : 4251)
1793 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1795 #pragma pack(push, 8)
1805 using namespace Json;
1806 void writeToStdout(StreamWriter::Factory const& factory, Value const& value) {
1807 std::unique_ptr<StreamWriter> const writer(
1808 factory.newStreamWriter());
1809 writer->write(value, &std::cout);
1810 std::cout << std::endl; // add lf and flush
1814 class JSON_API StreamWriter
{
1816 JSONCPP_OSTREAM
* sout_
; // not owned; will not delete
1819 virtual ~StreamWriter();
1820 /** Write Value into document as configured in sub-class.
1821 Do not take ownership of sout, but maintain a reference during function.
1823 \return zero on success (For now, we always return zero, so check the stream instead.)
1824 \throw std::exception possibly, depending on configuration
1826 virtual int write(Value
const& root
, JSONCPP_OSTREAM
* sout
) = 0;
1828 /** \brief A simple abstract factory.
1830 class JSON_API Factory
{
1833 /** \brief Allocate a CharReader via operator new().
1834 * \throw std::exception if something goes wrong (e.g. invalid settings)
1836 virtual StreamWriter
* newStreamWriter() const = 0;
1840 /** \brief Write into stringstream, then return string, for convenience.
1841 * A StreamWriter will be created from the factory, used, and then deleted.
1843 JSONCPP_STRING JSON_API
writeString(StreamWriter::Factory
const& factory
, Value
const& root
);
1846 /** \brief Build a StreamWriter implementation.
1850 using namespace Json;
1852 StreamWriterBuilder builder;
1853 builder["commentStyle"] = "None";
1854 builder["indentation"] = " "; // or whatever you like
1855 std::unique_ptr<Json::StreamWriter> writer(
1856 builder.newStreamWriter());
1857 writer->write(value, &std::cout);
1858 std::cout << std::endl; // add lf and flush
1861 class JSON_API StreamWriterBuilder
: public StreamWriter::Factory
{
1863 // Note: We use a Json::Value so that we can add data-members to this class
1864 // without a major version bump.
1865 /** Configuration of this builder.
1866 Available settings (case-sensitive):
1867 - "commentStyle": "None" or "All"
1868 - "indentation": "<anything>"
1869 - "enableYAMLCompatibility": false or true
1870 - slightly change the whitespace around colons
1871 - "dropNullPlaceholders": false or true
1872 - Drop the "null" string from the writer's output for nullValues.
1873 Strictly speaking, this is not valid JSON. But when the output is being
1874 fed to a browser's JavaScript, it makes for smaller output and the
1875 browser can handle the output just fine.
1876 - "useSpecialFloats": false or true
1877 - If true, outputs non-finite floating point values in the following way:
1878 NaN values as "NaN", positive infinity as "Infinity", and negative infinity
1881 You can examine 'settings_` yourself
1882 to see the defaults. You can also write and read them just like any
1886 Json::Value settings_
;
1888 StreamWriterBuilder();
1889 ~StreamWriterBuilder() JSONCPP_OVERRIDE
;
1892 * \throw std::exception if something goes wrong (e.g. invalid settings)
1894 StreamWriter
* newStreamWriter() const JSONCPP_OVERRIDE
;
1896 /** \return true if 'settings' are legal and consistent;
1897 * otherwise, indicate bad settings via 'invalid'.
1899 bool validate(Json::Value
* invalid
) const;
1900 /** A simple way to update a specific setting.
1902 Value
& operator[](JSONCPP_STRING key
);
1904 /** Called by ctor, but you can use this to reset settings_.
1905 * \pre 'settings' != NULL (but Json::null is fine)
1907 * \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults
1909 static void setDefaults(Json::Value
* settings
);
1912 /** \brief Abstract class for writers.
1913 * \deprecated Use StreamWriter. (And really, this is an implementation detail.)
1915 class JSONCPP_DEPRECATED("Use StreamWriter instead") JSON_API Writer
{
1919 virtual JSONCPP_STRING
write(const Value
& root
) = 0;
1922 /** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format
1923 *without formatting (not human friendly).
1925 * The JSON document is written in a single line. It is not intended for 'human'
1927 * but may be usefull to support feature such as RPC where bandwith is limited.
1929 * \deprecated Use StreamWriterBuilder.
1931 #if defined(_MSC_VER)
1932 #pragma warning(push)
1933 #pragma warning(disable:4996) // Deriving from deprecated class
1935 class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API FastWriter
: public Writer
{
1938 ~FastWriter() JSONCPP_OVERRIDE
{}
1940 void enableYAMLCompatibility();
1942 /** \brief Drop the "null" string from the writer's output for nullValues.
1943 * Strictly speaking, this is not valid JSON. But when the output is being
1944 * fed to a browser's JavaScript, it makes for smaller output and the
1945 * browser can handle the output just fine.
1947 void dropNullPlaceholders();
1949 void omitEndingLineFeed();
1951 public: // overridden from Writer
1952 JSONCPP_STRING
write(const Value
& root
) JSONCPP_OVERRIDE
;
1955 void writeValue(const Value
& value
);
1957 JSONCPP_STRING document_
;
1958 bool yamlCompatibilityEnabled_
;
1959 bool dropNullPlaceholders_
;
1960 bool omitEndingLineFeed_
;
1962 #if defined(_MSC_VER)
1963 #pragma warning(pop)
1966 /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
1967 *human friendly way.
1969 * The rules for line break and indent are as follow:
1971 * - if empty then print {} without indent and line break
1972 * - if not empty the print '{', line break & indent, print one value per
1974 * and then unindent and line break and print '}'.
1976 * - if empty then print [] without indent and line break
1977 * - if the array contains no object value, empty array or some other value
1979 * and all the values fit on one lines, then print the array on a single
1981 * - otherwise, it the values do not fit on one line, or the array contains
1982 * object or non empty array, then print one value per line.
1984 * If the Value have comments then they are outputed according to their
1987 * \sa Reader, Value, Value::setComment()
1988 * \deprecated Use StreamWriterBuilder.
1990 #if defined(_MSC_VER)
1991 #pragma warning(push)
1992 #pragma warning(disable:4996) // Deriving from deprecated class
1994 class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API StyledWriter
: public Writer
{
1997 ~StyledWriter() JSONCPP_OVERRIDE
{}
1999 public: // overridden from Writer
2000 /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
2001 * \param root Value to serialize.
2002 * \return String containing the JSON document that represents the root value.
2004 JSONCPP_STRING
write(const Value
& root
) JSONCPP_OVERRIDE
;
2007 void writeValue(const Value
& value
);
2008 void writeArrayValue(const Value
& value
);
2009 bool isMultilineArray(const Value
& value
);
2010 void pushValue(const JSONCPP_STRING
& value
);
2012 void writeWithIndent(const JSONCPP_STRING
& value
);
2015 void writeCommentBeforeValue(const Value
& root
);
2016 void writeCommentAfterValueOnSameLine(const Value
& root
);
2017 bool hasCommentForValue(const Value
& value
);
2018 static JSONCPP_STRING
normalizeEOL(const JSONCPP_STRING
& text
);
2020 typedef std::vector
<JSONCPP_STRING
> ChildValues
;
2022 ChildValues childValues_
;
2023 JSONCPP_STRING document_
;
2024 JSONCPP_STRING indentString_
;
2025 unsigned int rightMargin_
;
2026 unsigned int indentSize_
;
2027 bool addChildValues_
;
2029 #if defined(_MSC_VER)
2030 #pragma warning(pop)
2033 /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
2035 to a stream rather than to a string.
2037 * The rules for line break and indent are as follow:
2039 * - if empty then print {} without indent and line break
2040 * - if not empty the print '{', line break & indent, print one value per
2042 * and then unindent and line break and print '}'.
2044 * - if empty then print [] without indent and line break
2045 * - if the array contains no object value, empty array or some other value
2047 * and all the values fit on one lines, then print the array on a single
2049 * - otherwise, it the values do not fit on one line, or the array contains
2050 * object or non empty array, then print one value per line.
2052 * If the Value have comments then they are outputed according to their
2055 * \sa Reader, Value, Value::setComment()
2056 * \deprecated Use StreamWriterBuilder.
2058 #if defined(_MSC_VER)
2059 #pragma warning(push)
2060 #pragma warning(disable:4996) // Deriving from deprecated class
2062 class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API StyledStreamWriter
{
2065 * \param indentation Each level will be indented by this amount extra.
2067 StyledStreamWriter(JSONCPP_STRING indentation
= "\t");
2068 ~StyledStreamWriter() {}
2071 /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
2072 * \param out Stream to write to. (Can be ostringstream, e.g.)
2073 * \param root Value to serialize.
2074 * \note There is no point in deriving from Writer, since write() should not
2077 void write(JSONCPP_OSTREAM
& out
, const Value
& root
);
2080 void writeValue(const Value
& value
);
2081 void writeArrayValue(const Value
& value
);
2082 bool isMultilineArray(const Value
& value
);
2083 void pushValue(const JSONCPP_STRING
& value
);
2085 void writeWithIndent(const JSONCPP_STRING
& value
);
2088 void writeCommentBeforeValue(const Value
& root
);
2089 void writeCommentAfterValueOnSameLine(const Value
& root
);
2090 bool hasCommentForValue(const Value
& value
);
2091 static JSONCPP_STRING
normalizeEOL(const JSONCPP_STRING
& text
);
2093 typedef std::vector
<JSONCPP_STRING
> ChildValues
;
2095 ChildValues childValues_
;
2096 JSONCPP_OSTREAM
* document_
;
2097 JSONCPP_STRING indentString_
;
2098 unsigned int rightMargin_
;
2099 JSONCPP_STRING indentation_
;
2100 bool addChildValues_
: 1;
2103 #if defined(_MSC_VER)
2104 #pragma warning(pop)
2107 #if defined(JSON_HAS_INT64)
2108 JSONCPP_STRING JSON_API
valueToString(Int value
);
2109 JSONCPP_STRING JSON_API
valueToString(UInt value
);
2110 #endif // if defined(JSON_HAS_INT64)
2111 JSONCPP_STRING JSON_API
valueToString(LargestInt value
);
2112 JSONCPP_STRING JSON_API
valueToString(LargestUInt value
);
2113 JSONCPP_STRING JSON_API
valueToString(double value
);
2114 JSONCPP_STRING JSON_API
valueToString(bool value
);
2115 JSONCPP_STRING JSON_API
valueToQuotedString(const char* value
);
2117 /// \brief Output using the StyledStreamWriter.
2118 /// \see Json::operator>>()
2119 JSON_API JSONCPP_OSTREAM
& operator<<(JSONCPP_OSTREAM
&, const Value
& root
);
2125 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
2126 #pragma warning(pop)
2127 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
2129 #endif // JSON_WRITER_H_INCLUDED
2131 // //////////////////////////////////////////////////////////////////////
2132 // End of content of file: include/json/writer.h
2133 // //////////////////////////////////////////////////////////////////////
2140 // //////////////////////////////////////////////////////////////////////
2141 // Beginning of content of file: include/json/assertions.h
2142 // //////////////////////////////////////////////////////////////////////
2144 // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
2145 // Distributed under MIT license, or public domain if desired and
2146 // recognized in your jurisdiction.
2147 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
2149 #ifndef CPPTL_JSON_ASSERTIONS_H_INCLUDED
2150 #define CPPTL_JSON_ASSERTIONS_H_INCLUDED
2155 #if !defined(JSON_IS_AMALGAMATION)
2157 #endif // if !defined(JSON_IS_AMALGAMATION)
2159 /** It should not be possible for a maliciously designed file to
2160 * cause an abort() or seg-fault, so these macros are used only
2161 * for pre-condition violations and internal logic errors.
2163 #if JSON_USE_EXCEPTION
2165 // @todo <= add detail about condition in exception
2166 # define JSON_ASSERT(condition) \
2167 {if (!(condition)) {Json::throwLogicError( "assert json failed" );}}
2169 # define JSON_FAIL_MESSAGE(message) \
2171 JSONCPP_OSTRINGSTREAM oss; oss << message; \
2172 Json::throwLogicError(oss.str()); \
2176 #else // JSON_USE_EXCEPTION
2178 # define JSON_ASSERT(condition) assert(condition)
2180 // The call to assert() will show the failure message in debug builds. In
2181 // release builds we abort, for a core-dump or debugger.
2182 # define JSON_FAIL_MESSAGE(message) \
2184 JSONCPP_OSTRINGSTREAM oss; oss << message; \
2185 assert(false && oss.str().c_str()); \
2192 #define JSON_ASSERT_MESSAGE(condition, message) \
2193 if (!(condition)) { \
2194 JSON_FAIL_MESSAGE(message); \
2197 #endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED
2199 // //////////////////////////////////////////////////////////////////////
2200 // End of content of file: include/json/assertions.h
2201 // //////////////////////////////////////////////////////////////////////
2207 #endif //ifndef JSON_AMALGAMATED_H_INCLUDED