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.6.5"
91 # define JSONCPP_VERSION_MAJOR 1
92 # define JSONCPP_VERSION_MINOR 6
93 # define JSONCPP_VERSION_PATCH 5
94 # define JSONCPP_VERSION_QUALIFIER
95 # define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8))
97 #endif // JSON_VERSION_H_INCLUDED
99 // //////////////////////////////////////////////////////////////////////
100 // End of content of file: include/json/version.h
101 // //////////////////////////////////////////////////////////////////////
108 // //////////////////////////////////////////////////////////////////////
109 // Beginning of content of file: include/json/config.h
110 // //////////////////////////////////////////////////////////////////////
112 // Copyright 2007-2010 Baptiste Lepilleur
113 // Distributed under MIT license, or public domain if desired and
114 // recognized in your jurisdiction.
115 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
117 #ifndef JSON_CONFIG_H_INCLUDED
118 #define JSON_CONFIG_H_INCLUDED
120 /// If defined, indicates that json library is embedded in CppTL library.
121 //# define JSON_IN_CPPTL 1
123 /// If defined, indicates that json may leverage CppTL library
124 //# define JSON_USE_CPPTL 1
125 /// If defined, indicates that cpptl vector based map should be used instead of
127 /// as Value container.
128 //# define JSON_USE_CPPTL_SMALLMAP 1
130 // If non-zero, the library uses exceptions to report bad input instead of C
131 // assertion macros. The default is to use exceptions.
132 #ifndef JSON_USE_EXCEPTION
133 #define JSON_USE_EXCEPTION 1
136 /// If defined, indicates that the source file is amalgated
137 /// to prevent private header inclusion.
138 /// Remarks: it is automatically defined in the generated amalgated header.
139 // #define JSON_IS_AMALGAMATION
142 #include <cpptl/config.h>
143 #ifndef JSON_USE_CPPTL
144 #define JSON_USE_CPPTL 1
149 #define JSON_API CPPTL_API
150 #elif defined(JSON_DLL_BUILD)
151 #if defined(_MSC_VER)
152 #define JSON_API __declspec(dllexport)
153 #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
154 #endif // if defined(_MSC_VER)
155 #elif defined(JSON_DLL)
156 #if defined(_MSC_VER)
157 #define JSON_API __declspec(dllimport)
158 #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
159 #endif // if defined(_MSC_VER)
160 #endif // ifdef JSON_IN_CPPTL
161 #if !defined(JSON_API)
165 // If JSON_NO_INT64 is defined, then Json only support C++ "int" type for
167 // Storages, and 64 bits integer support is disabled.
168 // #define JSON_NO_INT64 1
170 #if defined(_MSC_VER) // MSVC
171 # if _MSC_VER <= 1200 // MSVC 6
172 // Microsoft Visual Studio 6 only support conversion from __int64 to double
173 // (no conversion from unsigned __int64).
174 # define JSON_USE_INT64_DOUBLE_CONVERSION 1
175 // Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255'
176 // characters in the debug information)
177 // All projects I've ever seen with VS6 were using this globally (not bothering
178 // with pragma push/pop).
179 # pragma warning(disable : 4786)
182 # if _MSC_VER >= 1500 // MSVC 2008
183 /// Indicates that the following function is deprecated.
184 # define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
187 #endif // defined(_MSC_VER)
190 #ifndef JSON_HAS_RVALUE_REFERENCES
192 #if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010
193 #define JSON_HAS_RVALUE_REFERENCES 1
194 #endif // MSVC >= 2010
197 #if __has_feature(cxx_rvalue_references)
198 #define JSON_HAS_RVALUE_REFERENCES 1
199 #endif // has_feature
201 #elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
202 #if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L)
203 #define JSON_HAS_RVALUE_REFERENCES 1
204 #endif // GXX_EXPERIMENTAL
206 #endif // __clang__ || __GNUC__
208 #endif // not defined JSON_HAS_RVALUE_REFERENCES
210 #ifndef JSON_HAS_RVALUE_REFERENCES
211 #define JSON_HAS_RVALUE_REFERENCES 0
215 #elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
216 # if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
217 # define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
218 # elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
219 # define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__))
220 # endif // GNUC version
221 #endif // __clang__ || __GNUC__
223 #if !defined(JSONCPP_DEPRECATED)
224 #define JSONCPP_DEPRECATED(message)
225 #endif // if !defined(JSONCPP_DEPRECATED)
229 typedef unsigned int UInt;
230 #if defined(JSON_NO_INT64)
231 typedef int LargestInt;
232 typedef unsigned int LargestUInt;
233 #undef JSON_HAS_INT64
234 #else // if defined(JSON_NO_INT64)
235 // For Microsoft Visual use specific types as long long is not supported
236 #if defined(_MSC_VER) // Microsoft Visual Studio
237 typedef __int64 Int64;
238 typedef unsigned __int64 UInt64;
239 #else // if defined(_MSC_VER) // Other platforms, use long long
240 typedef long long int Int64;
241 typedef unsigned long long int UInt64;
242 #endif // if defined(_MSC_VER)
243 typedef Int64 LargestInt;
244 typedef UInt64 LargestUInt;
245 #define JSON_HAS_INT64
246 #endif // if defined(JSON_NO_INT64)
247 } // end namespace Json
249 #endif // JSON_CONFIG_H_INCLUDED
251 // //////////////////////////////////////////////////////////////////////
252 // End of content of file: include/json/config.h
253 // //////////////////////////////////////////////////////////////////////
260 // //////////////////////////////////////////////////////////////////////
261 // Beginning of content of file: include/json/forwards.h
262 // //////////////////////////////////////////////////////////////////////
264 // Copyright 2007-2010 Baptiste Lepilleur
265 // Distributed under MIT license, or public domain if desired and
266 // recognized in your jurisdiction.
267 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
269 #ifndef JSON_FORWARDS_H_INCLUDED
270 #define JSON_FORWARDS_H_INCLUDED
272 #if !defined(JSON_IS_AMALGAMATION)
274 #endif // if !defined(JSON_IS_AMALGAMATION)
289 typedef unsigned int ArrayIndex;
294 class ValueIteratorBase;
296 class ValueConstIterator;
300 #endif // JSON_FORWARDS_H_INCLUDED
302 // //////////////////////////////////////////////////////////////////////
303 // End of content of file: include/json/forwards.h
304 // //////////////////////////////////////////////////////////////////////
311 // //////////////////////////////////////////////////////////////////////
312 // Beginning of content of file: include/json/features.h
313 // //////////////////////////////////////////////////////////////////////
315 // Copyright 2007-2010 Baptiste Lepilleur
316 // Distributed under MIT license, or public domain if desired and
317 // recognized in your jurisdiction.
318 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
320 #ifndef CPPTL_JSON_FEATURES_H_INCLUDED
321 #define CPPTL_JSON_FEATURES_H_INCLUDED
323 #if !defined(JSON_IS_AMALGAMATION)
324 #include "forwards.h"
325 #endif // if !defined(JSON_IS_AMALGAMATION)
329 /** \brief Configuration passed to reader and writer.
330 * This configuration object can be used to force the Reader or Writer
331 * to behave in a standard conforming way.
333 class JSON_API Features {
335 /** \brief A configuration that allows all features and assumes all strings
337 * - C & C++ comments are allowed
338 * - Root object can be any JSON value
339 * - Assumes Value strings are encoded in UTF-8
341 static Features all();
343 /** \brief A configuration that is strictly compatible with the JSON
345 * - Comments are forbidden.
346 * - Root object must be either an array or an object value.
347 * - Assumes Value strings are encoded in UTF-8
349 static Features strictMode();
351 /** \brief Initialize the configuration like JsonConfig::allFeatures;
355 /// \c true if comments are allowed. Default: \c true.
358 /// \c true if root must be either an array or an object value. Default: \c
362 /// \c true if dropped null placeholders are allowed. Default: \c false.
363 bool allowDroppedNullPlaceholders_;
365 /// \c true if numeric object key are allowed. Default: \c false.
366 bool allowNumericKeys_;
371 #endif // CPPTL_JSON_FEATURES_H_INCLUDED
373 // //////////////////////////////////////////////////////////////////////
374 // End of content of file: include/json/features.h
375 // //////////////////////////////////////////////////////////////////////
382 // //////////////////////////////////////////////////////////////////////
383 // Beginning of content of file: include/json/value.h
384 // //////////////////////////////////////////////////////////////////////
386 // Copyright 2007-2010 Baptiste Lepilleur
387 // Distributed under MIT license, or public domain if desired and
388 // recognized in your jurisdiction.
389 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
391 #ifndef CPPTL_JSON_H_INCLUDED
392 #define CPPTL_JSON_H_INCLUDED
394 #if !defined(JSON_IS_AMALGAMATION)
395 #include "forwards.h"
396 #endif // if !defined(JSON_IS_AMALGAMATION)
401 #ifndef JSON_USE_CPPTL_SMALLMAP
404 #include <cpptl/smallmap.h>
406 #ifdef JSON_USE_CPPTL
407 #include <cpptl/forwards.h>
410 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
412 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
413 #pragma warning(push)
414 #pragma warning(disable : 4251)
415 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
417 /** \brief JSON (JavaScript Object Notation).
421 /** Base class for all exceptions we throw.
423 * We use nothing but these internally. Of course, STL can throw others.
425 class JSON_API Exception : public std::exception {
427 Exception(std::string const& msg);
428 ~Exception() throw() override;
429 char const* what() const throw() override;
434 /** Exceptions which the user cannot easily avoid.
436 * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
438 * \remark derived from Json::Exception
440 class JSON_API RuntimeError : public Exception {
442 RuntimeError(std::string const& msg);
445 /** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
447 * These are precondition-violations (user bugs) and internal errors (our bugs).
449 * \remark derived from Json::Exception
451 class JSON_API LogicError : public Exception {
453 LogicError(std::string const& msg);
457 void throwRuntimeError(std::string const& msg);
459 void throwLogicError(std::string const& msg);
461 /** \brief Type of the value held by a Value object.
464 nullValue = 0, ///< 'null' value
465 intValue, ///< signed integer value
466 uintValue, ///< unsigned integer value
467 realValue, ///< double value
468 stringValue, ///< UTF-8 string value
469 booleanValue, ///< bool value
470 arrayValue, ///< array value (ordered list)
471 objectValue ///< object value (collection of name/value pairs).
474 enum CommentPlacement {
475 commentBefore = 0, ///< a comment placed on the line before a value
476 commentAfterOnSameLine, ///< a comment just after a value on the same line
477 commentAfter, ///< a comment on the line after a value (only make sense for
479 numberOfCommentPlacement
482 //# ifdef JSON_USE_CPPTL
483 // typedef CppTL::AnyEnumerator<const char *> EnumMemberNames;
484 // typedef CppTL::AnyEnumerator<const Value &> EnumValues;
487 /** \brief Lightweight wrapper to tag static string.
489 * Value constructor and objectValue member assignement takes advantage of the
490 * StaticString and avoid the cost of string duplication when storing the
491 * string or the member name.
495 * Json::Value aValue( StaticString("some text") );
496 * Json::Value object;
497 * static const StaticString code("code");
498 * object[code] = 1234;
501 class JSON_API StaticString {
503 explicit StaticString(const char* czstring) : c_str_(czstring) {}
505 operator const char*() const { return c_str_; }
507 const char* c_str() const { return c_str_; }
513 /** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
515 * This class is a discriminated union wrapper that can represents a:
516 * - signed integer [range: Value::minInt - Value::maxInt]
517 * - unsigned integer (range: 0 - Value::maxUInt)
522 * - an ordered list of Value
523 * - collection of name/value pairs (javascript object)
525 * The type of the held value is represented by a #ValueType and
526 * can be obtained using type().
528 * Values of an #objectValue or #arrayValue can be accessed using operator[]()
530 * Non-const methods will automatically create the a #nullValue element
531 * if it does not exist.
532 * The sequence of an #arrayValue will be automatically resized and initialized
533 * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
535 * The get() methods can be used to obtain default value in the case the
536 * required element does not exist.
538 * It is possible to iterate over the list of a #objectValue values using
539 * the getMemberNames() method.
541 * \note #Value string-length fit in size_t, but keys must be < 2^30.
542 * (The reason is an implementation detail.) A #CharReader will raise an
543 * exception if a bound is exceeded to avoid security holes in your app,
544 * but the Value API does *not* check bounds. That is the responsibility
547 class JSON_API Value {
548 friend class ValueIteratorBase;
550 typedef std::vector<std::string> Members;
551 typedef ValueIterator iterator;
552 typedef ValueConstIterator const_iterator;
553 typedef Json::UInt UInt;
554 typedef Json::Int Int;
555 #if defined(JSON_HAS_INT64)
556 typedef Json::UInt64 UInt64;
557 typedef Json::Int64 Int64;
558 #endif // defined(JSON_HAS_INT64)
559 typedef Json::LargestInt LargestInt;
560 typedef Json::LargestUInt LargestUInt;
561 typedef Json::ArrayIndex ArrayIndex;
563 static const Value& null; ///< We regret this reference to a global instance; prefer the simpler Value().
564 static const Value& nullRef; ///< just a kludge for binary-compatibility; same as null
565 /// Minimum signed integer value that can be stored in a Json::Value.
566 static const LargestInt minLargestInt;
567 /// Maximum signed integer value that can be stored in a Json::Value.
568 static const LargestInt maxLargestInt;
569 /// Maximum unsigned integer value that can be stored in a Json::Value.
570 static const LargestUInt maxLargestUInt;
572 /// Minimum signed int value that can be stored in a Json::Value.
573 static const Int minInt;
574 /// Maximum signed int value that can be stored in a Json::Value.
575 static const Int maxInt;
576 /// Maximum unsigned int value that can be stored in a Json::Value.
577 static const UInt maxUInt;
579 #if defined(JSON_HAS_INT64)
580 /// Minimum signed 64 bits int value that can be stored in a Json::Value.
581 static const Int64 minInt64;
582 /// Maximum signed 64 bits int value that can be stored in a Json::Value.
583 static const Int64 maxInt64;
584 /// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
585 static const UInt64 maxUInt64;
586 #endif // defined(JSON_HAS_INT64)
589 #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
592 enum DuplicationPolicy {
597 CZString(ArrayIndex index);
598 CZString(char const* str, unsigned length, DuplicationPolicy allocate);
599 CZString(CZString const& other);
600 #if JSON_HAS_RVALUE_REFERENCES
601 CZString(CZString&& other);
604 CZString& operator=(CZString other);
605 bool operator<(CZString const& other) const;
606 bool operator==(CZString const& other) const;
607 ArrayIndex index() const;
608 //const char* c_str() const; ///< \deprecated
609 char const* data() const;
610 unsigned length() const;
611 bool isStaticString() const;
614 void swap(CZString& other);
616 struct StringStorage {
618 unsigned length_: 30; // 1GB max
621 char const* cstr_; // actually, a prefixed string, unless policy is noDup
624 StringStorage storage_;
629 #ifndef JSON_USE_CPPTL_SMALLMAP
630 typedef std::map<CZString, Value> ObjectValues;
632 typedef CppTL::SmallMap<CZString, Value> ObjectValues;
633 #endif // ifndef JSON_USE_CPPTL_SMALLMAP
634 #endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
637 /** \brief Create a default Value of the given type.
639 This is a very useful constructor.
640 To create an empty array, pass arrayValue.
641 To create an empty object, pass objectValue.
642 Another Value can then be set to this one by assignment.
643 This is useful since clear() and resize() will not alter types.
647 Json::Value null_value; // null
648 Json::Value arr_value(Json::arrayValue); // []
649 Json::Value obj_value(Json::objectValue); // {}
652 Value(ValueType type = nullValue);
655 #if defined(JSON_HAS_INT64)
658 #endif // if defined(JSON_HAS_INT64)
660 Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.)
661 Value(const char* begin, const char* end); ///< Copy all, incl zeroes.
662 /** \brief Constructs a value from a static string.
664 * Like other value string constructor but do not duplicate the string for
665 * internal storage. The given string must remain alive after the call to this
667 * \note This works only for null-terminated strings. (We cannot change the
668 * size of this class, so we have nowhere to store the length,
669 * which might be computed later for various operations.)
673 * static StaticString foo("some text");
674 * Json::Value aValue(foo);
677 Value(const StaticString& value);
678 Value(const std::string& value); ///< Copy data() til size(). Embedded zeroes too.
679 #ifdef JSON_USE_CPPTL
680 Value(const CppTL::ConstString& value);
684 Value(const Value& other);
685 #if JSON_HAS_RVALUE_REFERENCES
687 Value(Value&& other);
691 /// Deep copy, then swap(other).
692 /// \note Over-write existing comments. To preserve comments, use #swapPayload().
693 Value& operator=(Value other);
695 void swap(Value& other);
696 /// Swap values but leave comments and source offsets in place.
697 void swapPayload(Value& other);
699 ValueType type() const;
701 /// Compare payload only, not comments etc.
702 bool operator<(const Value& other) const;
703 bool operator<=(const Value& other) const;
704 bool operator>=(const Value& other) const;
705 bool operator>(const Value& other) const;
706 bool operator==(const Value& other) const;
707 bool operator!=(const Value& other) const;
708 int compare(const Value& other) const;
710 const char* asCString() const; ///< Embedded zeroes could cause you trouble!
711 std::string asString() const; ///< Embedded zeroes are possible.
712 /** Get raw char* of string-value.
713 * \return false if !string. (Seg-fault if str or end are NULL.)
716 char const** begin, char const** end) const;
717 #ifdef JSON_USE_CPPTL
718 CppTL::ConstString asConstString() const;
722 #if defined(JSON_HAS_INT64)
723 Int64 asInt64() const;
724 UInt64 asUInt64() const;
725 #endif // if defined(JSON_HAS_INT64)
726 LargestInt asLargestInt() const;
727 LargestUInt asLargestUInt() const;
728 float asFloat() const;
729 double asDouble() const;
735 bool isInt64() const;
737 bool isUInt64() const;
738 bool isIntegral() const;
739 bool isDouble() const;
740 bool isNumeric() const;
741 bool isString() const;
742 bool isArray() const;
743 bool isObject() const;
745 bool isConvertibleTo(ValueType other) const;
747 /// Number of values in array or object
748 ArrayIndex size() const;
750 /// \brief Return true if empty array, empty object, or null;
751 /// otherwise, false.
755 bool operator!() const;
757 /// Remove all object members and array elements.
758 /// \pre type() is arrayValue, objectValue, or nullValue
759 /// \post type() is unchanged
762 /// Resize the array to size elements.
763 /// New elements are initialized to null.
764 /// May only be called on nullValue or arrayValue.
765 /// \pre type() is arrayValue or nullValue
766 /// \post type() is arrayValue
767 void resize(ArrayIndex size);
769 /// Access an array element (zero based index ).
770 /// If the array contains less than index element, then null value are
772 /// in the array so that its size is index+1.
773 /// (You may need to say 'value[0u]' to get your compiler to distinguish
774 /// this from the operator[] which takes a string.)
775 Value& operator[](ArrayIndex index);
777 /// Access an array element (zero based index ).
778 /// If the array contains less than index element, then null value are
780 /// in the array so that its size is index+1.
781 /// (You may need to say 'value[0u]' to get your compiler to distinguish
782 /// this from the operator[] which takes a string.)
783 Value& operator[](int index);
785 /// Access an array element (zero based index )
786 /// (You may need to say 'value[0u]' to get your compiler to distinguish
787 /// this from the operator[] which takes a string.)
788 const Value& operator[](ArrayIndex index) const;
790 /// Access an array element (zero based index )
791 /// (You may need to say 'value[0u]' to get your compiler to distinguish
792 /// this from the operator[] which takes a string.)
793 const Value& operator[](int index) const;
795 /// If the array contains at least index+1 elements, returns the element
797 /// otherwise returns defaultValue.
798 Value get(ArrayIndex index, const Value& defaultValue) const;
799 /// Return true if index < size().
800 bool isValidIndex(ArrayIndex index) const;
801 /// \brief Append value to array at the end.
803 /// Equivalent to jsonvalue[jsonvalue.size()] = value;
804 Value& append(const Value& value);
806 /// Access an object value by name, create a null member if it does not exist.
807 /// \note Because of our implementation, keys are limited to 2^30 -1 chars.
808 /// Exceeding that will cause an exception.
809 Value& operator[](const char* key);
810 /// Access an object value by name, returns null if there is no member with
812 const Value& operator[](const char* key) const;
813 /// Access an object value by name, create a null member if it does not exist.
814 /// \param key may contain embedded nulls.
815 Value& operator[](const std::string& key);
816 /// Access an object value by name, returns null if there is no member with
818 /// \param key may contain embedded nulls.
819 const Value& operator[](const std::string& key) const;
820 /** \brief Access an object value by name, create a null member if it does not
823 * If the object has no entry for that name, then the member name used to store
824 * the new entry is not duplicated.
827 * Json::Value object;
828 * static const StaticString code("code");
829 * object[code] = 1234;
832 Value& operator[](const StaticString& key);
833 #ifdef JSON_USE_CPPTL
834 /// Access an object value by name, create a null member if it does not exist.
835 Value& operator[](const CppTL::ConstString& key);
836 /// Access an object value by name, returns null if there is no member with
838 const Value& operator[](const CppTL::ConstString& key) const;
840 /// Return the member named key if it exist, defaultValue otherwise.
842 Value get(const char* key, const Value& defaultValue) const;
843 /// Return the member named key if it exist, defaultValue otherwise.
845 /// \note key may contain embedded nulls.
846 Value get(const char* begin, const char* end, const Value& defaultValue) const;
847 /// Return the member named key if it exist, defaultValue otherwise.
849 /// \param key may contain embedded nulls.
850 Value get(const std::string& key, const Value& defaultValue) const;
851 #ifdef JSON_USE_CPPTL
852 /// Return the member named key if it exist, defaultValue otherwise.
854 Value get(const CppTL::ConstString& key, const Value& defaultValue) const;
856 /// Most general and efficient version of isMember()const, get()const,
857 /// and operator[]const
858 /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
859 Value const* find(char const* begin, char const* end) const;
860 /// Most general and efficient version of object-mutators.
861 /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
862 /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
863 Value const* demand(char const* begin, char const* end);
864 /// \brief Remove and return the named member.
866 /// Do nothing if it did not exist.
867 /// \return the removed Value, or null.
868 /// \pre type() is objectValue or nullValue
869 /// \post type() is unchanged
871 Value removeMember(const char* key);
872 /// Same as removeMember(const char*)
873 /// \param key may contain embedded nulls.
875 Value removeMember(const std::string& key);
876 /// Same as removeMember(const char* begin, const char* end, Value* removed),
877 /// but 'key' is null-terminated.
878 bool removeMember(const char* key, Value* removed);
879 /** \brief Remove the named map member.
881 Update 'removed' iff removed.
882 \param key may contain embedded nulls.
883 \return true iff removed (no exceptions)
885 bool removeMember(std::string const& key, Value* removed);
886 /// Same as removeMember(std::string const& key, Value* removed)
887 bool removeMember(const char* begin, const char* end, Value* removed);
888 /** \brief Remove the indexed array element.
890 O(n) expensive operations.
891 Update 'removed' iff removed.
892 \return true iff removed (no exceptions)
894 bool removeIndex(ArrayIndex i, Value* removed);
896 /// Return true if the object has a member named key.
897 /// \note 'key' must be null-terminated.
898 bool isMember(const char* key) const;
899 /// Return true if the object has a member named key.
900 /// \param key may contain embedded nulls.
901 bool isMember(const std::string& key) const;
902 /// Same as isMember(std::string const& key)const
903 bool isMember(const char* begin, const char* end) const;
904 #ifdef JSON_USE_CPPTL
905 /// Return true if the object has a member named key.
906 bool isMember(const CppTL::ConstString& key) const;
909 /// \brief Return a list of the member names.
911 /// If null, return an empty list.
912 /// \pre type() is objectValue or nullValue
913 /// \post if type() was nullValue, it remains nullValue
914 Members getMemberNames() const;
916 //# ifdef JSON_USE_CPPTL
917 // EnumMemberNames enumMemberNames() const;
918 // EnumValues enumValues() const;
921 /// \deprecated Always pass len.
922 JSONCPP_DEPRECATED("Use setComment(std::string const&) instead.")
923 void setComment(const char* comment, CommentPlacement placement);
924 /// Comments must be //... or /* ... */
925 void setComment(const char* comment, size_t len, CommentPlacement placement);
926 /// Comments must be //... or /* ... */
927 void setComment(const std::string& comment, CommentPlacement placement);
928 bool hasComment(CommentPlacement placement) const;
929 /// Include delimiters and embedded newlines.
930 std::string getComment(CommentPlacement placement) const;
932 std::string toStyledString() const;
934 const_iterator begin() const;
935 const_iterator end() const;
940 // Accessors for the [start, limit) range of bytes within the JSON text from
941 // which this value was parsed, if any.
942 void setOffsetStart(size_t start);
943 void setOffsetLimit(size_t limit);
944 size_t getOffsetStart() const;
945 size_t getOffsetLimit() const;
948 void initBasic(ValueType type, bool allocated = false);
950 Value& resolveReference(const char* key);
951 Value& resolveReference(const char* key, const char* end);
957 void setComment(const char* text, size_t len);
962 // struct MemberNamesTransform
964 // typedef const char *result_type;
965 // const char *operator()( const CZString &name ) const
967 // return name.c_str();
976 char* string_; // actually ptr to unsigned, followed by str, unless !allocated_
980 unsigned int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
981 // If not allocated_, string_ must be null-terminated.
982 CommentInfo* comments_;
984 // [start, limit) byte offsets in the source JSON text from which this Value
990 /** \brief Experimental and untested: represents an element of the "path" to
993 class JSON_API PathArgument {
998 PathArgument(ArrayIndex index);
999 PathArgument(const char* key);
1000 PathArgument(const std::string& key);
1013 /** \brief Experimental and untested: represents a "path" to access a node.
1016 * - "." => root node
1017 * - ".[n]" => elements at index 'n' of root node (an array value)
1018 * - ".name" => member named 'name' of root node (an object value)
1019 * - ".name1.name2.name3"
1020 * - ".[0][1][2].name1[3]"
1021 * - ".%" => member name is provided as parameter
1022 * - ".[%]" => index is provied as parameter
1024 class JSON_API Path {
1026 Path(const std::string& path,
1027 const PathArgument& a1 = PathArgument(),
1028 const PathArgument& a2 = PathArgument(),
1029 const PathArgument& a3 = PathArgument(),
1030 const PathArgument& a4 = PathArgument(),
1031 const PathArgument& a5 = PathArgument());
1033 const Value& resolve(const Value& root) const;
1034 Value resolve(const Value& root, const Value& defaultValue) const;
1035 /// Creates the "path" to access the specified node and returns a reference on
1037 Value& make(Value& root) const;
1040 typedef std::vector<const PathArgument*> InArgs;
1041 typedef std::vector<PathArgument> Args;
1043 void makePath(const std::string& path, const InArgs& in);
1044 void addPathInArg(const std::string& path,
1046 InArgs::const_iterator& itInArg,
1047 PathArgument::Kind kind);
1048 void invalidPath(const std::string& path, int location);
1053 /** \brief base class for Value iterators.
1056 class JSON_API ValueIteratorBase {
1058 typedef std::bidirectional_iterator_tag iterator_category;
1059 typedef unsigned int size_t;
1060 typedef int difference_type;
1061 typedef ValueIteratorBase SelfType;
1063 bool operator==(const SelfType& other) const { return isEqual(other); }
1065 bool operator!=(const SelfType& other) const { return !isEqual(other); }
1067 difference_type operator-(const SelfType& other) const {
1068 return other.computeDistance(*this);
1071 /// Return either the index or the member name of the referenced value as a
1075 /// Return the index of the referenced Value, or -1 if it is not an arrayValue.
1078 /// Return the member name of the referenced Value, or "" if it is not an
1080 /// \note Avoid `c_str()` on result, as embedded zeroes are possible.
1081 std::string name() const;
1083 /// Return the member name of the referenced Value. "" if it is not an
1085 /// \deprecated This cannot be used for UTF-8 strings, since there can be embedded nulls.
1086 JSONCPP_DEPRECATED("Use `key = name();` instead.")
1087 char const* memberName() const;
1088 /// Return the member name of the referenced Value, or NULL if it is not an
1090 /// \note Better version than memberName(). Allows embedded nulls.
1091 char const* memberName(char const** end) const;
1094 Value& deref() const;
1100 difference_type computeDistance(const SelfType& other) const;
1102 bool isEqual(const SelfType& other) const;
1104 void copy(const SelfType& other);
1107 Value::ObjectValues::iterator current_;
1108 // Indicates that iterator is for a null value.
1112 // For some reason, BORLAND needs these at the end, rather
1113 // than earlier. No idea why.
1114 ValueIteratorBase();
1115 explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
1118 /** \brief const iterator for object and array value.
1121 class JSON_API ValueConstIterator : public ValueIteratorBase {
1125 typedef const Value value_type;
1126 //typedef unsigned int size_t;
1127 //typedef int difference_type;
1128 typedef const Value& reference;
1129 typedef const Value* pointer;
1130 typedef ValueConstIterator SelfType;
1132 ValueConstIterator();
1133 ValueConstIterator(ValueIterator const& other);
1136 /*! \internal Use by Value to create an iterator.
1138 explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
1140 SelfType& operator=(const ValueIteratorBase& other);
1142 SelfType operator++(int) {
1143 SelfType temp(*this);
1148 SelfType operator--(int) {
1149 SelfType temp(*this);
1154 SelfType& operator--() {
1159 SelfType& operator++() {
1164 reference operator*() const { return deref(); }
1166 pointer operator->() const { return &deref(); }
1169 /** \brief Iterator for object and array value.
1171 class JSON_API ValueIterator : public ValueIteratorBase {
1175 typedef Value value_type;
1176 typedef unsigned int size_t;
1177 typedef int difference_type;
1178 typedef Value& reference;
1179 typedef Value* pointer;
1180 typedef ValueIterator SelfType;
1183 explicit ValueIterator(const ValueConstIterator& other);
1184 ValueIterator(const ValueIterator& other);
1187 /*! \internal Use by Value to create an iterator.
1189 explicit ValueIterator(const Value::ObjectValues::iterator& current);
1191 SelfType& operator=(const SelfType& other);
1193 SelfType operator++(int) {
1194 SelfType temp(*this);
1199 SelfType operator--(int) {
1200 SelfType temp(*this);
1205 SelfType& operator--() {
1210 SelfType& operator++() {
1215 reference operator*() const { return deref(); }
1217 pointer operator->() const { return &deref(); }
1224 /// Specialize std::swap() for Json::Value.
1226 inline void swap(Json::Value& a, Json::Value& b) { a.swap(b); }
1230 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1231 #pragma warning(pop)
1232 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1234 #endif // CPPTL_JSON_H_INCLUDED
1236 // //////////////////////////////////////////////////////////////////////
1237 // End of content of file: include/json/value.h
1238 // //////////////////////////////////////////////////////////////////////
1245 // //////////////////////////////////////////////////////////////////////
1246 // Beginning of content of file: include/json/reader.h
1247 // //////////////////////////////////////////////////////////////////////
1249 // Copyright 2007-2010 Baptiste Lepilleur
1250 // Distributed under MIT license, or public domain if desired and
1251 // recognized in your jurisdiction.
1252 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1254 #ifndef CPPTL_JSON_READER_H_INCLUDED
1255 #define CPPTL_JSON_READER_H_INCLUDED
1257 #if !defined(JSON_IS_AMALGAMATION)
1258 #include "features.h"
1260 #endif // if !defined(JSON_IS_AMALGAMATION)
1267 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
1269 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1270 #pragma warning(push)
1271 #pragma warning(disable : 4251)
1272 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1276 /** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a
1279 * \deprecated Use CharReader and CharReaderBuilder.
1281 class JSON_API Reader {
1284 typedef const Char* Location;
1286 /** \brief An error tagged with where in the JSON text it was encountered.
1288 * The offsets give the [start, limit) range of bytes within the text. Note
1289 * that this is bytes, not codepoints.
1292 struct StructuredError {
1293 size_t offset_start;
1294 size_t offset_limit;
1295 std::string message;
1298 /** \brief Constructs a Reader allowing all features
1303 /** \brief Constructs a Reader allowing the specified feature set
1306 Reader(const Features& features);
1308 /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1310 * \param document UTF-8 encoded string containing the document to read.
1311 * \param root [out] Contains the root value of the document if it was
1312 * successfully parsed.
1313 * \param collectComments \c true to collect comment and allow writing them
1315 * serialization, \c false to discard comments.
1316 * This parameter is ignored if
1317 * Features::allowComments_
1319 * \return \c true if the document was successfully parsed, \c false if an
1323 parse(const std::string& document, Value& root, bool collectComments = true);
1325 /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1327 * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
1329 * \param endDoc Pointer on the end of the UTF-8 encoded string of the
1331 * Must be >= beginDoc.
1332 * \param root [out] Contains the root value of the document if it was
1333 * successfully parsed.
1334 * \param collectComments \c true to collect comment and allow writing them
1336 * serialization, \c false to discard comments.
1337 * This parameter is ignored if
1338 Features::allowComments_
1340 * \return \c true if the document was successfully parsed, \c false if an
1343 bool parse(const char* beginDoc,
1346 bool collectComments = true);
1348 /// \brief Parse from input stream.
1349 /// \see Json::operator>>(std::istream&, Json::Value&).
1350 bool parse(std::istream& is, Value& root, bool collectComments = true);
1352 /** \brief Returns a user friendly string that list errors in the parsed
1354 * \return Formatted error message with the list of errors with their location
1356 * the parsed document. An empty string is returned if no error
1359 * \deprecated Use getFormattedErrorMessages() instead (typo fix).
1361 JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.")
1362 std::string getFormatedErrorMessages() const;
1364 /** \brief Returns a user friendly string that list errors in the parsed
1366 * \return Formatted error message with the list of errors with their location
1368 * the parsed document. An empty string is returned if no error
1372 std::string getFormattedErrorMessages() const;
1374 /** \brief Returns a vector of structured erros encounted while parsing.
1375 * \return A (possibly empty) vector of StructuredError objects. Currently
1376 * only one error can be returned, but the caller should tolerate
1378 * errors. This can occur if the parser recovers from a non-fatal
1379 * parse error and then encounters additional errors.
1381 std::vector<StructuredError> getStructuredErrors() const;
1383 /** \brief Add a semantic error message.
1384 * \param value JSON Value location associated with the error
1385 * \param message The error message.
1386 * \return \c true if the error was successfully added, \c false if the
1387 * Value offset exceeds the document size.
1389 bool pushError(const Value& value, const std::string& message);
1391 /** \brief Add a semantic error message with extra context.
1392 * \param value JSON Value location associated with the error
1393 * \param message The error message.
1394 * \param extra Additional JSON Value location to contextualize the error
1395 * \return \c true if the error was successfully added, \c false if either
1396 * Value offset exceeds the document size.
1398 bool pushError(const Value& value, const std::string& message, const Value& extra);
1400 /** \brief Return whether there are any errors.
1401 * \return \c true if there are no errors to report \c false if
1402 * errors have occurred.
1408 tokenEndOfStream = 0,
1418 tokenArraySeparator,
1419 tokenMemberSeparator,
1434 std::string message_;
1438 typedef std::deque<ErrorInfo> Errors;
1440 bool readToken(Token& token);
1442 bool match(Location pattern, int patternLength);
1444 bool readCStyleComment();
1445 bool readCppStyleComment();
1449 bool readObject(Token& token);
1450 bool readArray(Token& token);
1451 bool decodeNumber(Token& token);
1452 bool decodeNumber(Token& token, Value& decoded);
1453 bool decodeString(Token& token);
1454 bool decodeString(Token& token, std::string& decoded);
1455 bool decodeDouble(Token& token);
1456 bool decodeDouble(Token& token, Value& decoded);
1457 bool decodeUnicodeCodePoint(Token& token,
1460 unsigned int& unicode);
1461 bool decodeUnicodeEscapeSequence(Token& token,
1464 unsigned int& unicode);
1465 bool addError(const std::string& message, Token& token, Location extra = 0);
1466 bool recoverFromError(TokenType skipUntilToken);
1467 bool addErrorAndRecover(const std::string& message,
1469 TokenType skipUntilToken);
1470 void skipUntilSpace();
1471 Value& currentValue();
1474 getLocationLineAndColumn(Location location, int& line, int& column) const;
1475 std::string getLocationLineAndColumn(Location location) const;
1476 void addComment(Location begin, Location end, CommentPlacement placement);
1477 void skipCommentTokens(Token& token);
1479 typedef std::stack<Value*> Nodes;
1482 std::string document_;
1486 Location lastValueEnd_;
1488 std::string commentsBefore_;
1490 bool collectComments_;
1493 /** Interface for reading JSON from a char array.
1495 class JSON_API CharReader {
1497 virtual ~CharReader() {}
1498 /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1500 * The document must be a UTF-8 encoded string containing the document to read.
1502 * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
1504 * \param endDoc Pointer on the end of the UTF-8 encoded string of the
1506 * Must be >= beginDoc.
1507 * \param root [out] Contains the root value of the document if it was
1508 * successfully parsed.
1509 * \param errs [out] Formatted error messages (if not NULL)
1510 * a user friendly string that lists errors in the parsed
1512 * \return \c true if the document was successfully parsed, \c false if an
1516 char const* beginDoc, char const* endDoc,
1517 Value* root, std::string* errs) = 0;
1519 class JSON_API Factory {
1521 virtual ~Factory() {}
1522 /** \brief Allocate a CharReader via operator new().
1523 * \throw std::exception if something goes wrong (e.g. invalid settings)
1525 virtual CharReader* newCharReader() const = 0;
1529 /** \brief Build a CharReader implementation.
1533 using namespace Json;
1534 CharReaderBuilder builder;
1535 builder["collectComments"] = false;
1538 bool ok = parseFromStream(builder, std::cin, &value, &errs);
1541 class JSON_API CharReaderBuilder : public CharReader::Factory {
1543 // Note: We use a Json::Value so that we can add data-members to this class
1544 // without a major version bump.
1545 /** Configuration of this builder.
1546 These are case-sensitive.
1547 Available settings (case-sensitive):
1548 - `"collectComments": false or true`
1549 - true to collect comment and allow writing them
1550 back during serialization, false to discard comments.
1551 This parameter is ignored if allowComments is false.
1552 - `"allowComments": false or true`
1553 - true if comments are allowed.
1554 - `"strictRoot": false or true`
1555 - true if root must be either an array or an object value
1556 - `"allowDroppedNullPlaceholders": false or true`
1557 - true if dropped null placeholders are allowed. (See StreamWriterBuilder.)
1558 - `"allowNumericKeys": false or true`
1559 - true if numeric object keys are allowed.
1560 - `"allowSingleQuotes": false or true`
1561 - true if '' are allowed for strings (both keys and values)
1562 - `"stackLimit": integer`
1563 - Exceeding stackLimit (recursive depth of `readValue()`) will
1565 - This is a security issue (seg-faults caused by deeply nested JSON),
1566 so the default is low.
1567 - `"failIfExtra": false or true`
1568 - If true, `parse()` returns false when extra non-whitespace trails
1569 the JSON value in the input string.
1570 - `"rejectDupKeys": false or true`
1571 - If true, `parse()` returns false when a key is duplicated within an object.
1572 - `"allowSpecialFloats": false or true`
1573 - If true, special float values (NaNs and infinities) are allowed
1574 and their values are lossfree restorable.
1576 You can examine 'settings_` yourself
1577 to see the defaults. You can also write and read them just like any
1581 Json::Value settings_;
1583 CharReaderBuilder();
1584 ~CharReaderBuilder() override;
1586 CharReader* newCharReader() const override;
1588 /** \return true if 'settings' are legal and consistent;
1589 * otherwise, indicate bad settings via 'invalid'.
1591 bool validate(Json::Value* invalid) const;
1593 /** A simple way to update a specific setting.
1595 Value& operator[](std::string key);
1597 /** Called by ctor, but you can use this to reset settings_.
1598 * \pre 'settings' != NULL (but Json::null is fine)
1600 * \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults
1602 static void setDefaults(Json::Value* settings);
1603 /** Same as old Features::strictMode().
1604 * \pre 'settings' != NULL (but Json::null is fine)
1606 * \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode
1608 static void strictMode(Json::Value* settings);
1611 /** Consume entire stream and use its begin/end.
1612 * Someday we might have a real StreamReader, but for now this
1615 bool JSON_API parseFromStream(
1616 CharReader::Factory const&,
1618 Value* root, std::string* errs);
1620 /** \brief Read from 'sin' into 'root'.
1622 Always keep comments from the input JSON.
1624 This can be used to read a file into a particular sub-object.
1628 cin >> root["dir"]["file"];
1636 // The input stream JSON would be nested here.
1641 \throw std::exception on parse error.
1642 \see Json::operator<<()
1644 JSON_API std::istream& operator>>(std::istream&, Value&);
1648 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1649 #pragma warning(pop)
1650 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1652 #endif // CPPTL_JSON_READER_H_INCLUDED
1654 // //////////////////////////////////////////////////////////////////////
1655 // End of content of file: include/json/reader.h
1656 // //////////////////////////////////////////////////////////////////////
1663 // //////////////////////////////////////////////////////////////////////
1664 // Beginning of content of file: include/json/writer.h
1665 // //////////////////////////////////////////////////////////////////////
1667 // Copyright 2007-2010 Baptiste Lepilleur
1668 // Distributed under MIT license, or public domain if desired and
1669 // recognized in your jurisdiction.
1670 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1672 #ifndef JSON_WRITER_H_INCLUDED
1673 #define JSON_WRITER_H_INCLUDED
1675 #if !defined(JSON_IS_AMALGAMATION)
1677 #endif // if !defined(JSON_IS_AMALGAMATION)
1682 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
1684 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1685 #pragma warning(push)
1686 #pragma warning(disable : 4251)
1687 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1697 using namespace Json;
1698 void writeToStdout(StreamWriter::Factory const& factory, Value const& value) {
1699 std::unique_ptr<StreamWriter> const writer(
1700 factory.newStreamWriter());
1701 writer->write(value, &std::cout);
1702 std::cout << std::endl; // add lf and flush
1706 class JSON_API StreamWriter {
1708 std::ostream* sout_; // not owned; will not delete
1711 virtual ~StreamWriter();
1712 /** Write Value into document as configured in sub-class.
1713 Do not take ownership of sout, but maintain a reference during function.
1715 \return zero on success (For now, we always return zero, so check the stream instead.)
1716 \throw std::exception possibly, depending on configuration
1718 virtual int write(Value const& root, std::ostream* sout) = 0;
1720 /** \brief A simple abstract factory.
1722 class JSON_API Factory {
1725 /** \brief Allocate a CharReader via operator new().
1726 * \throw std::exception if something goes wrong (e.g. invalid settings)
1728 virtual StreamWriter* newStreamWriter() const = 0;
1732 /** \brief Write into stringstream, then return string, for convenience.
1733 * A StreamWriter will be created from the factory, used, and then deleted.
1735 std::string JSON_API writeString(StreamWriter::Factory const& factory, Value const& root);
1738 /** \brief Build a StreamWriter implementation.
1742 using namespace Json;
1744 StreamWriterBuilder builder;
1745 builder["commentStyle"] = "None";
1746 builder["indentation"] = " "; // or whatever you like
1747 std::unique_ptr<Json::StreamWriter> writer(
1748 builder.newStreamWriter());
1749 writer->write(value, &std::cout);
1750 std::cout << std::endl; // add lf and flush
1753 class JSON_API StreamWriterBuilder : public StreamWriter::Factory {
1755 // Note: We use a Json::Value so that we can add data-members to this class
1756 // without a major version bump.
1757 /** Configuration of this builder.
1758 Available settings (case-sensitive):
1759 - "commentStyle": "None" or "All"
1760 - "indentation": "<anything>"
1761 - "enableYAMLCompatibility": false or true
1762 - slightly change the whitespace around colons
1763 - "dropNullPlaceholders": false or true
1764 - Drop the "null" string from the writer's output for nullValues.
1765 Strictly speaking, this is not valid JSON. But when the output is being
1766 fed to a browser's Javascript, it makes for smaller output and the
1767 browser can handle the output just fine.
1768 - "useSpecialFloats": false or true
1769 - If true, outputs non-finite floating point values in the following way:
1770 NaN values as "NaN", positive infinity as "Infinity", and negative infinity
1773 You can examine 'settings_` yourself
1774 to see the defaults. You can also write and read them just like any
1778 Json::Value settings_;
1780 StreamWriterBuilder();
1781 ~StreamWriterBuilder() override;
1784 * \throw std::exception if something goes wrong (e.g. invalid settings)
1786 StreamWriter* newStreamWriter() const override;
1788 /** \return true if 'settings' are legal and consistent;
1789 * otherwise, indicate bad settings via 'invalid'.
1791 bool validate(Json::Value* invalid) const;
1792 /** A simple way to update a specific setting.
1794 Value& operator[](std::string key);
1796 /** Called by ctor, but you can use this to reset settings_.
1797 * \pre 'settings' != NULL (but Json::null is fine)
1799 * \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults
1801 static void setDefaults(Json::Value* settings);
1804 /** \brief Abstract class for writers.
1805 * \deprecated Use StreamWriter. (And really, this is an implementation detail.)
1807 class JSON_API Writer {
1811 virtual std::string write(const Value& root) = 0;
1814 /** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format
1815 *without formatting (not human friendly).
1817 * The JSON document is written in a single line. It is not intended for 'human'
1819 * but may be usefull to support feature such as RPC where bandwith is limited.
1821 * \deprecated Use StreamWriterBuilder.
1823 class JSON_API FastWriter : public Writer {
1827 ~FastWriter() override {}
1829 void enableYAMLCompatibility();
1831 /** \brief Drop the "null" string from the writer's output for nullValues.
1832 * Strictly speaking, this is not valid JSON. But when the output is being
1833 * fed to a browser's Javascript, it makes for smaller output and the
1834 * browser can handle the output just fine.
1836 void dropNullPlaceholders();
1838 void omitEndingLineFeed();
1840 public: // overridden from Writer
1841 std::string write(const Value& root) override;
1844 void writeValue(const Value& value);
1846 std::string document_;
1847 bool yamlCompatiblityEnabled_;
1848 bool dropNullPlaceholders_;
1849 bool omitEndingLineFeed_;
1852 /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
1853 *human friendly way.
1855 * The rules for line break and indent are as follow:
1857 * - if empty then print {} without indent and line break
1858 * - if not empty the print '{', line break & indent, print one value per
1860 * and then unindent and line break and print '}'.
1862 * - if empty then print [] without indent and line break
1863 * - if the array contains no object value, empty array or some other value
1865 * and all the values fit on one lines, then print the array on a single
1867 * - otherwise, it the values do not fit on one line, or the array contains
1868 * object or non empty array, then print one value per line.
1870 * If the Value have comments then they are outputed according to their
1873 * \sa Reader, Value, Value::setComment()
1874 * \deprecated Use StreamWriterBuilder.
1876 class JSON_API StyledWriter : public Writer {
1879 ~StyledWriter() override {}
1881 public: // overridden from Writer
1882 /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
1883 * \param root Value to serialize.
1884 * \return String containing the JSON document that represents the root value.
1886 std::string write(const Value& root) override;
1889 void writeValue(const Value& value);
1890 void writeArrayValue(const Value& value);
1891 bool isMultineArray(const Value& value);
1892 void pushValue(const std::string& value);
1894 void writeWithIndent(const std::string& value);
1897 void writeCommentBeforeValue(const Value& root);
1898 void writeCommentAfterValueOnSameLine(const Value& root);
1899 bool hasCommentForValue(const Value& value);
1900 static std::string normalizeEOL(const std::string& text);
1902 typedef std::vector<std::string> ChildValues;
1904 ChildValues childValues_;
1905 std::string document_;
1906 std::string indentString_;
1909 bool addChildValues_;
1912 /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
1914 to a stream rather than to a string.
1916 * The rules for line break and indent are as follow:
1918 * - if empty then print {} without indent and line break
1919 * - if not empty the print '{', line break & indent, print one value per
1921 * and then unindent and line break and print '}'.
1923 * - if empty then print [] without indent and line break
1924 * - if the array contains no object value, empty array or some other value
1926 * and all the values fit on one lines, then print the array on a single
1928 * - otherwise, it the values do not fit on one line, or the array contains
1929 * object or non empty array, then print one value per line.
1931 * If the Value have comments then they are outputed according to their
1934 * \param indentation Each level will be indented by this amount extra.
1935 * \sa Reader, Value, Value::setComment()
1936 * \deprecated Use StreamWriterBuilder.
1938 class JSON_API StyledStreamWriter {
1940 StyledStreamWriter(std::string indentation = "\t");
1941 ~StyledStreamWriter() {}
1944 /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
1945 * \param out Stream to write to. (Can be ostringstream, e.g.)
1946 * \param root Value to serialize.
1947 * \note There is no point in deriving from Writer, since write() should not
1950 void write(std::ostream& out, const Value& root);
1953 void writeValue(const Value& value);
1954 void writeArrayValue(const Value& value);
1955 bool isMultineArray(const Value& value);
1956 void pushValue(const std::string& value);
1958 void writeWithIndent(const std::string& value);
1961 void writeCommentBeforeValue(const Value& root);
1962 void writeCommentAfterValueOnSameLine(const Value& root);
1963 bool hasCommentForValue(const Value& value);
1964 static std::string normalizeEOL(const std::string& text);
1966 typedef std::vector<std::string> ChildValues;
1968 ChildValues childValues_;
1969 std::ostream* document_;
1970 std::string indentString_;
1972 std::string indentation_;
1973 bool addChildValues_ : 1;
1977 #if defined(JSON_HAS_INT64)
1978 std::string JSON_API valueToString(Int value);
1979 std::string JSON_API valueToString(UInt value);
1980 #endif // if defined(JSON_HAS_INT64)
1981 std::string JSON_API valueToString(LargestInt value);
1982 std::string JSON_API valueToString(LargestUInt value);
1983 std::string JSON_API valueToString(double value);
1984 std::string JSON_API valueToString(bool value);
1985 std::string JSON_API valueToQuotedString(const char* value);
1987 /// \brief Output using the StyledStreamWriter.
1988 /// \see Json::operator>>()
1989 JSON_API std::ostream& operator<<(std::ostream&, const Value& root);
1993 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1994 #pragma warning(pop)
1995 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1997 #endif // JSON_WRITER_H_INCLUDED
1999 // //////////////////////////////////////////////////////////////////////
2000 // End of content of file: include/json/writer.h
2001 // //////////////////////////////////////////////////////////////////////
2008 // //////////////////////////////////////////////////////////////////////
2009 // Beginning of content of file: include/json/assertions.h
2010 // //////////////////////////////////////////////////////////////////////
2012 // Copyright 2007-2010 Baptiste Lepilleur
2013 // Distributed under MIT license, or public domain if desired and
2014 // recognized in your jurisdiction.
2015 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
2017 #ifndef CPPTL_JSON_ASSERTIONS_H_INCLUDED
2018 #define CPPTL_JSON_ASSERTIONS_H_INCLUDED
2023 #if !defined(JSON_IS_AMALGAMATION)
2025 #endif // if !defined(JSON_IS_AMALGAMATION)
2027 /** It should not be possible for a maliciously designed file to
2028 * cause an abort() or seg-fault, so these macros are used only
2029 * for pre-condition violations and internal logic errors.
2031 #if JSON_USE_EXCEPTION
2033 // @todo <= add detail about condition in exception
2034 # define JSON_ASSERT(condition) \
2035 {if (!(condition)) {Json::throwLogicError( "assert json failed" );}}
2037 # define JSON_FAIL_MESSAGE(message) \
2039 std::ostringstream oss; oss << message; \
2040 Json::throwLogicError(oss.str()); \
2044 #else // JSON_USE_EXCEPTION
2046 # define JSON_ASSERT(condition) assert(condition)
2048 // The call to assert() will show the failure message in debug builds. In
2049 // release builds we abort, for a core-dump or debugger.
2050 # define JSON_FAIL_MESSAGE(message) \
2052 std::ostringstream oss; oss << message; \
2053 assert(false && oss.str().c_str()); \
2060 #define JSON_ASSERT_MESSAGE(condition, message) \
2061 if (!(condition)) { \
2062 JSON_FAIL_MESSAGE(message); \
2065 #endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED
2067 // //////////////////////////////////////////////////////////////////////
2068 // End of content of file: include/json/assertions.h
2069 // //////////////////////////////////////////////////////////////////////
2075 #endif //ifndef JSON_AMALGATED_H_INCLUDED