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
80 #define JSONCPP_STRING
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 "0.10.6"
91 # define JSONCPP_VERSION_MAJOR 0
92 # define JSONCPP_VERSION_MINOR 10
93 # define JSONCPP_VERSION_PATCH 6
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) && _MSC_VER <= 1200 // MSVC 6
171 // Microsoft Visual Studio 6 only support conversion from __int64 to double
172 // (no conversion from unsigned __int64).
173 #define JSON_USE_INT64_DOUBLE_CONVERSION 1
174 // Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255'
175 // characters in the debug information)
176 // All projects I've ever seen with VS6 were using this globally (not bothering
177 // with pragma push/pop).
178 #pragma warning(disable : 4786)
179 #endif // if defined(_MSC_VER) && _MSC_VER < 1200 // MSVC 6
181 #if defined(_MSC_VER) && _MSC_VER >= 1500 // MSVC 2008
182 /// Indicates that the following function is deprecated.
183 #define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
184 #elif defined(__clang__) && defined(__has_feature)
185 #if __has_feature(attribute_deprecated_with_message)
186 #define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
188 #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
189 #define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
190 #elif defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
191 #define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__))
194 #if !defined(JSONCPP_DEPRECATED)
195 #define JSONCPP_DEPRECATED(message)
196 #endif // if !defined(JSONCPP_DEPRECATED)
200 typedef unsigned int UInt;
201 #if defined(JSON_NO_INT64)
202 typedef int LargestInt;
203 typedef unsigned int LargestUInt;
204 #undef JSON_HAS_INT64
205 #else // if defined(JSON_NO_INT64)
206 // For Microsoft Visual use specific types as long long is not supported
207 #if defined(_MSC_VER) // Microsoft Visual Studio
208 typedef __int64 Int64;
209 typedef unsigned __int64 UInt64;
210 #else // if defined(_MSC_VER) // Other platforms, use long long
211 typedef long long int Int64;
212 typedef unsigned long long int UInt64;
213 #endif // if defined(_MSC_VER)
214 typedef Int64 LargestInt;
215 typedef UInt64 LargestUInt;
216 #define JSON_HAS_INT64
217 #endif // if defined(JSON_NO_INT64)
218 } // end namespace Json
220 #endif // JSON_CONFIG_H_INCLUDED
222 // //////////////////////////////////////////////////////////////////////
223 // End of content of file: include/json/config.h
224 // //////////////////////////////////////////////////////////////////////
231 // //////////////////////////////////////////////////////////////////////
232 // Beginning of content of file: include/json/forwards.h
233 // //////////////////////////////////////////////////////////////////////
235 // Copyright 2007-2010 Baptiste Lepilleur
236 // Distributed under MIT license, or public domain if desired and
237 // recognized in your jurisdiction.
238 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
240 #ifndef JSON_FORWARDS_H_INCLUDED
241 #define JSON_FORWARDS_H_INCLUDED
243 #if !defined(JSON_IS_AMALGAMATION)
245 #endif // if !defined(JSON_IS_AMALGAMATION)
260 typedef unsigned int ArrayIndex;
265 class ValueIteratorBase;
267 class ValueConstIterator;
271 #endif // JSON_FORWARDS_H_INCLUDED
273 // //////////////////////////////////////////////////////////////////////
274 // End of content of file: include/json/forwards.h
275 // //////////////////////////////////////////////////////////////////////
282 // //////////////////////////////////////////////////////////////////////
283 // Beginning of content of file: include/json/features.h
284 // //////////////////////////////////////////////////////////////////////
286 // Copyright 2007-2010 Baptiste Lepilleur
287 // Distributed under MIT license, or public domain if desired and
288 // recognized in your jurisdiction.
289 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
291 #ifndef CPPTL_JSON_FEATURES_H_INCLUDED
292 #define CPPTL_JSON_FEATURES_H_INCLUDED
294 #if !defined(JSON_IS_AMALGAMATION)
295 #include "forwards.h"
296 #endif // if !defined(JSON_IS_AMALGAMATION)
300 /** \brief Configuration passed to reader and writer.
301 * This configuration object can be used to force the Reader or Writer
302 * to behave in a standard conforming way.
304 class JSON_API Features {
306 /** \brief A configuration that allows all features and assumes all strings
308 * - C & C++ comments are allowed
309 * - Root object can be any JSON value
310 * - Assumes Value strings are encoded in UTF-8
312 static Features all();
314 /** \brief A configuration that is strictly compatible with the JSON
316 * - Comments are forbidden.
317 * - Root object must be either an array or an object value.
318 * - Assumes Value strings are encoded in UTF-8
320 static Features strictMode();
322 /** \brief Initialize the configuration like JsonConfig::allFeatures;
326 /// \c true if comments are allowed. Default: \c true.
329 /// \c true if root must be either an array or an object value. Default: \c
336 #endif // CPPTL_JSON_FEATURES_H_INCLUDED
338 // //////////////////////////////////////////////////////////////////////
339 // End of content of file: include/json/features.h
340 // //////////////////////////////////////////////////////////////////////
347 // //////////////////////////////////////////////////////////////////////
348 // Beginning of content of file: include/json/value.h
349 // //////////////////////////////////////////////////////////////////////
351 // Copyright 2007-2010 Baptiste Lepilleur
352 // Distributed under MIT license, or public domain if desired and
353 // recognized in your jurisdiction.
354 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
356 #ifndef CPPTL_JSON_H_INCLUDED
357 #define CPPTL_JSON_H_INCLUDED
359 #if !defined(JSON_IS_AMALGAMATION)
360 #include "forwards.h"
361 #endif // if !defined(JSON_IS_AMALGAMATION)
366 #ifndef JSON_USE_CPPTL_SMALLMAP
369 #include <cpptl/smallmap.h>
371 #ifdef JSON_USE_CPPTL
372 #include <cpptl/forwards.h>
375 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
377 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
378 #pragma warning(push)
379 #pragma warning(disable : 4251)
380 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
382 //Conditional NORETURN attribute on the throw functions would:
383 // a) suppress false positives from static code analysis
384 // b) possibly improve optimization opportunities.
385 #if !defined(JSONCPP_NORETURN)
386 # if defined(_MSC_VER)
387 # define JSONCPP_NORETURN __declspec(noreturn)
388 # elif defined(__GNUC__)
389 # define JSONCPP_NORETURN __attribute__ ((__noreturn__))
391 # define JSONCPP_NORETURN
395 /** \brief JSON (JavaScript Object Notation).
399 /** Base class for all exceptions we throw.
401 * We use nothing but these internally. Of course, STL can throw others.
403 class JSON_API Exception : public std::exception {
405 Exception(std::string const& msg);
406 virtual ~Exception() throw();
407 virtual char const* what() const throw();
409 std::string const msg_;
412 /** Exceptions which the user cannot easily avoid.
414 * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
416 * \remark derived from Json::Exception
418 class JSON_API RuntimeError : public Exception {
420 RuntimeError(std::string const& msg);
423 /** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
425 * These are precondition-violations (user bugs) and internal errors (our bugs).
427 * \remark derived from Json::Exception
429 class JSON_API LogicError : public Exception {
431 LogicError(std::string const& msg);
435 JSONCPP_NORETURN void throwRuntimeError(std::string const& msg);
437 JSONCPP_NORETURN void throwLogicError(std::string const& msg);
439 /** \brief Type of the value held by a Value object.
442 nullValue = 0, ///< 'null' value
443 intValue, ///< signed integer value
444 uintValue, ///< unsigned integer value
445 realValue, ///< double value
446 stringValue, ///< UTF-8 string value
447 booleanValue, ///< bool value
448 arrayValue, ///< array value (ordered list)
449 objectValue ///< object value (collection of name/value pairs).
452 enum CommentPlacement {
453 commentBefore = 0, ///< a comment placed on the line before a value
454 commentAfterOnSameLine, ///< a comment just after a value on the same line
455 commentAfter, ///< a comment on the line after a value (only make sense for
457 numberOfCommentPlacement
460 //# ifdef JSON_USE_CPPTL
461 // typedef CppTL::AnyEnumerator<const char *> EnumMemberNames;
462 // typedef CppTL::AnyEnumerator<const Value &> EnumValues;
465 /** \brief Lightweight wrapper to tag static string.
467 * Value constructor and objectValue member assignement takes advantage of the
468 * StaticString and avoid the cost of string duplication when storing the
469 * string or the member name.
473 * Json::Value aValue( StaticString("some text") );
474 * Json::Value object;
475 * static const StaticString code("code");
476 * object[code] = 1234;
479 class JSON_API StaticString {
481 explicit StaticString(const char* czstring) : c_str_(czstring) {}
483 operator const char*() const { return c_str_; }
485 const char* c_str() const { return c_str_; }
491 /** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
493 * This class is a discriminated union wrapper that can represents a:
494 * - signed integer [range: Value::minInt - Value::maxInt]
495 * - unsigned integer (range: 0 - Value::maxUInt)
500 * - an ordered list of Value
501 * - collection of name/value pairs (javascript object)
503 * The type of the held value is represented by a #ValueType and
504 * can be obtained using type().
506 * Values of an #objectValue or #arrayValue can be accessed using operator[]()
508 * Non-const methods will automatically create the a #nullValue element
509 * if it does not exist.
510 * The sequence of an #arrayValue will be automatically resized and initialized
511 * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
513 * The get() methods can be used to obtain default value in the case the
514 * required element does not exist.
516 * It is possible to iterate over the list of a #objectValue values using
517 * the getMemberNames() method.
519 * \note #Value string-length fit in size_t, but keys must be < 2^30.
520 * (The reason is an implementation detail.) A #CharReader will raise an
521 * exception if a bound is exceeded to avoid security holes in your app,
522 * but the Value API does *not* check bounds. That is the responsibility
525 class JSON_API Value {
526 friend class ValueIteratorBase;
528 typedef std::vector<std::string> Members;
529 typedef ValueIterator iterator;
530 typedef ValueConstIterator const_iterator;
531 typedef Json::UInt UInt;
532 typedef Json::Int Int;
533 #if defined(JSON_HAS_INT64)
534 typedef Json::UInt64 UInt64;
535 typedef Json::Int64 Int64;
536 #endif // defined(JSON_HAS_INT64)
537 typedef Json::LargestInt LargestInt;
538 typedef Json::LargestUInt LargestUInt;
539 typedef Json::ArrayIndex ArrayIndex;
541 static const Value& nullRef;
542 #if !defined(__ARMEL__)
543 /// \deprecated This exists for binary compatibility only. Use nullRef.
544 static const Value null;
546 /// Minimum signed integer value that can be stored in a Json::Value.
547 static const LargestInt minLargestInt;
548 /// Maximum signed integer value that can be stored in a Json::Value.
549 static const LargestInt maxLargestInt;
550 /// Maximum unsigned integer value that can be stored in a Json::Value.
551 static const LargestUInt maxLargestUInt;
553 /// Minimum signed int value that can be stored in a Json::Value.
554 static const Int minInt;
555 /// Maximum signed int value that can be stored in a Json::Value.
556 static const Int maxInt;
557 /// Maximum unsigned int value that can be stored in a Json::Value.
558 static const UInt maxUInt;
560 #if defined(JSON_HAS_INT64)
561 /// Minimum signed 64 bits int value that can be stored in a Json::Value.
562 static const Int64 minInt64;
563 /// Maximum signed 64 bits int value that can be stored in a Json::Value.
564 static const Int64 maxInt64;
565 /// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
566 static const UInt64 maxUInt64;
567 #endif // defined(JSON_HAS_INT64)
570 #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
573 enum DuplicationPolicy {
578 CZString(ArrayIndex index);
579 CZString(char const* str, unsigned length, DuplicationPolicy allocate);
580 CZString(CZString const& other);
582 CZString& operator=(CZString other);
583 bool operator<(CZString const& other) const;
584 bool operator==(CZString const& other) const;
585 ArrayIndex index() const;
586 //const char* c_str() const; ///< \deprecated
587 char const* data() const;
588 unsigned length() const;
589 bool isStaticString() const;
592 void swap(CZString& other);
594 struct StringStorage {
596 unsigned length_: 30; // 1GB max
599 char const* cstr_; // actually, a prefixed string, unless policy is noDup
602 StringStorage storage_;
607 #ifndef JSON_USE_CPPTL_SMALLMAP
608 typedef std::map<CZString, Value> ObjectValues;
610 typedef CppTL::SmallMap<CZString, Value> ObjectValues;
611 #endif // ifndef JSON_USE_CPPTL_SMALLMAP
612 #endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
615 /** \brief Create a default Value of the given type.
617 This is a very useful constructor.
618 To create an empty array, pass arrayValue.
619 To create an empty object, pass objectValue.
620 Another Value can then be set to this one by assignment.
621 This is useful since clear() and resize() will not alter types.
625 Json::Value null_value; // null
626 Json::Value arr_value(Json::arrayValue); // []
627 Json::Value obj_value(Json::objectValue); // {}
630 Value(ValueType type = nullValue);
633 #if defined(JSON_HAS_INT64)
636 #endif // if defined(JSON_HAS_INT64)
638 Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.)
639 Value(const char* begin, const char* end); ///< Copy all, incl zeroes.
640 /** \brief Constructs a value from a static string.
642 * Like other value string constructor but do not duplicate the string for
643 * internal storage. The given string must remain alive after the call to this
645 * \note This works only for null-terminated strings. (We cannot change the
646 * size of this class, so we have nowhere to store the length,
647 * which might be computed later for various operations.)
651 * static StaticString foo("some text");
652 * Json::Value aValue(foo);
655 Value(const StaticString& value);
656 Value(const std::string& value); ///< Copy data() til size(). Embedded zeroes too.
657 #ifdef JSON_USE_CPPTL
658 Value(const CppTL::ConstString& value);
662 Value(const Value& other);
665 /// Deep copy, then swap(other).
666 /// \note Over-write existing comments. To preserve comments, use #swapPayload().
667 Value &operator=(const Value &other);
669 void swap(Value& other);
670 /// Swap values but leave comments and source offsets in place.
671 void swapPayload(Value& other);
673 ValueType type() const;
675 /// Compare payload only, not comments etc.
676 bool operator<(const Value& other) const;
677 bool operator<=(const Value& other) const;
678 bool operator>=(const Value& other) const;
679 bool operator>(const Value& other) const;
680 bool operator==(const Value& other) const;
681 bool operator!=(const Value& other) const;
682 int compare(const Value& other) const;
684 const char* asCString() const; ///< Embedded zeroes could cause you trouble!
685 std::string asString() const; ///< Embedded zeroes are possible.
686 /** Get raw char* of string-value.
687 * \return false if !string. (Seg-fault if str or end are NULL.)
690 char const** begin, char const** end) const;
691 #ifdef JSON_USE_CPPTL
692 CppTL::ConstString asConstString() const;
696 #if defined(JSON_HAS_INT64)
697 Int64 asInt64() const;
698 UInt64 asUInt64() const;
699 #endif // if defined(JSON_HAS_INT64)
700 LargestInt asLargestInt() const;
701 LargestUInt asLargestUInt() const;
702 float asFloat() const;
703 double asDouble() const;
709 bool isInt64() const;
711 bool isUInt64() const;
712 bool isIntegral() const;
713 bool isDouble() const;
714 bool isNumeric() const;
715 bool isString() const;
716 bool isArray() const;
717 bool isObject() const;
719 bool isConvertibleTo(ValueType other) const;
721 /// Number of values in array or object
722 ArrayIndex size() const;
724 /// \brief Return true if empty array, empty object, or null;
725 /// otherwise, false.
729 bool operator!() const;
731 /// Remove all object members and array elements.
732 /// \pre type() is arrayValue, objectValue, or nullValue
733 /// \post type() is unchanged
736 /// Resize the array to size elements.
737 /// New elements are initialized to null.
738 /// May only be called on nullValue or arrayValue.
739 /// \pre type() is arrayValue or nullValue
740 /// \post type() is arrayValue
741 void resize(ArrayIndex size);
743 /// Access an array element (zero based index ).
744 /// If the array contains less than index element, then null value are
746 /// in the array so that its size is index+1.
747 /// (You may need to say 'value[0u]' to get your compiler to distinguish
748 /// this from the operator[] which takes a string.)
749 Value& operator[](ArrayIndex index);
751 /// Access an array element (zero based index ).
752 /// If the array contains less than index element, then null value are
754 /// in the array so that its size is index+1.
755 /// (You may need to say 'value[0u]' to get your compiler to distinguish
756 /// this from the operator[] which takes a string.)
757 Value& operator[](int index);
759 /// Access an array element (zero based index )
760 /// (You may need to say 'value[0u]' to get your compiler to distinguish
761 /// this from the operator[] which takes a string.)
762 const Value& operator[](ArrayIndex index) const;
764 /// Access an array element (zero based index )
765 /// (You may need to say 'value[0u]' to get your compiler to distinguish
766 /// this from the operator[] which takes a string.)
767 const Value& operator[](int index) const;
769 /// If the array contains at least index+1 elements, returns the element
771 /// otherwise returns defaultValue.
772 Value get(ArrayIndex index, const Value& defaultValue) const;
773 /// Return true if index < size().
774 bool isValidIndex(ArrayIndex index) const;
775 /// \brief Append value to array at the end.
777 /// Equivalent to jsonvalue[jsonvalue.size()] = value;
778 Value& append(const Value& value);
780 /// Access an object value by name, create a null member if it does not exist.
781 /// \note Because of our implementation, keys are limited to 2^30 -1 chars.
782 /// Exceeding that will cause an exception.
783 Value& operator[](const char* key);
784 /// Access an object value by name, returns null if there is no member with
786 const Value& operator[](const char* key) const;
787 /// Access an object value by name, create a null member if it does not exist.
788 /// \param key may contain embedded nulls.
789 Value& operator[](const std::string& key);
790 /// Access an object value by name, returns null if there is no member with
792 /// \param key may contain embedded nulls.
793 const Value& operator[](const std::string& key) const;
794 /** \brief Access an object value by name, create a null member if it does not
797 * If the object has no entry for that name, then the member name used to store
798 * the new entry is not duplicated.
801 * Json::Value object;
802 * static const StaticString code("code");
803 * object[code] = 1234;
806 Value& operator[](const StaticString& key);
807 #ifdef JSON_USE_CPPTL
808 /// Access an object value by name, create a null member if it does not exist.
809 Value& operator[](const CppTL::ConstString& key);
810 /// Access an object value by name, returns null if there is no member with
812 const Value& operator[](const CppTL::ConstString& key) const;
814 /// Return the member named key if it exist, defaultValue otherwise.
816 Value get(const char* key, const Value& defaultValue) const;
817 /// Return the member named key if it exist, defaultValue otherwise.
819 /// \note key may contain embedded nulls.
820 Value get(const char* begin, const char* end, const Value& defaultValue) const;
821 /// Return the member named key if it exist, defaultValue otherwise.
823 /// \param key may contain embedded nulls.
824 Value get(const std::string& key, const Value& defaultValue) const;
825 #ifdef JSON_USE_CPPTL
826 /// Return the member named key if it exist, defaultValue otherwise.
828 Value get(const CppTL::ConstString& key, const Value& defaultValue) const;
830 /// Most general and efficient version of isMember()const, get()const,
831 /// and operator[]const
832 /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
833 Value const* find(char const* begin, char const* end) const;
834 /// Most general and efficient version of object-mutators.
835 /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
836 /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
837 Value const* demand(char const* begin, char const* end);
838 /// \brief Remove and return the named member.
840 /// Do nothing if it did not exist.
841 /// \return the removed Value, or null.
842 /// \pre type() is objectValue or nullValue
843 /// \post type() is unchanged
845 Value removeMember(const char* key);
846 /// Same as removeMember(const char*)
847 /// \param key may contain embedded nulls.
849 Value removeMember(const std::string& key);
850 /// Same as removeMember(const char* begin, const char* end, Value* removed),
851 /// but 'key' is null-terminated.
852 bool removeMember(const char* key, Value* removed);
853 /** \brief Remove the named map member.
855 Update 'removed' iff removed.
856 \param key may contain embedded nulls.
857 \return true iff removed (no exceptions)
859 bool removeMember(std::string const& key, Value* removed);
860 /// Same as removeMember(std::string const& key, Value* removed)
861 bool removeMember(const char* begin, const char* end, Value* removed);
862 /** \brief Remove the indexed array element.
864 O(n) expensive operations.
865 Update 'removed' iff removed.
866 \return true iff removed (no exceptions)
868 bool removeIndex(ArrayIndex i, Value* removed);
870 /// Return true if the object has a member named key.
871 /// \note 'key' must be null-terminated.
872 bool isMember(const char* key) const;
873 /// Return true if the object has a member named key.
874 /// \param key may contain embedded nulls.
875 bool isMember(const std::string& key) const;
876 /// Same as isMember(std::string const& key)const
877 bool isMember(const char* begin, const char* end) const;
878 #ifdef JSON_USE_CPPTL
879 /// Return true if the object has a member named key.
880 bool isMember(const CppTL::ConstString& key) const;
883 /// \brief Return a list of the member names.
885 /// If null, return an empty list.
886 /// \pre type() is objectValue or nullValue
887 /// \post if type() was nullValue, it remains nullValue
888 Members getMemberNames() const;
890 //# ifdef JSON_USE_CPPTL
891 // EnumMemberNames enumMemberNames() const;
892 // EnumValues enumValues() const;
895 /// \deprecated Always pass len.
896 JSONCPP_DEPRECATED("Use setComment(std::string const&) instead.")
897 void setComment(const char* comment, CommentPlacement placement);
898 /// Comments must be //... or /* ... */
899 void setComment(const char* comment, size_t len, CommentPlacement placement);
900 /// Comments must be //... or /* ... */
901 void setComment(const std::string& comment, CommentPlacement placement);
902 bool hasComment(CommentPlacement placement) const;
903 /// Include delimiters and embedded newlines.
904 std::string getComment(CommentPlacement placement) const;
906 std::string toStyledString() const;
908 const_iterator begin() const;
909 const_iterator end() const;
915 void initBasic(ValueType type, bool allocated = false);
917 Value& resolveReference(const char* key);
918 Value& resolveReference(const char* key, const char* end);
924 void setComment(const char* text, size_t len);
929 // struct MemberNamesTransform
931 // typedef const char *result_type;
932 // const char *operator()( const CZString &name ) const
934 // return name.c_str();
943 char* string_; // actually ptr to unsigned, followed by str, unless !allocated_
947 unsigned int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
948 // If not allocated_, string_ must be null-terminated.
949 CommentInfo* comments_;
952 /** \brief Experimental and untested: represents an element of the "path" to
955 class JSON_API PathArgument {
960 PathArgument(ArrayIndex index);
961 PathArgument(const char* key);
962 PathArgument(const std::string& key);
975 /** \brief Experimental and untested: represents a "path" to access a node.
979 * - ".[n]" => elements at index 'n' of root node (an array value)
980 * - ".name" => member named 'name' of root node (an object value)
981 * - ".name1.name2.name3"
982 * - ".[0][1][2].name1[3]"
983 * - ".%" => member name is provided as parameter
984 * - ".[%]" => index is provied as parameter
986 class JSON_API Path {
988 Path(const std::string& path,
989 const PathArgument& a1 = PathArgument(),
990 const PathArgument& a2 = PathArgument(),
991 const PathArgument& a3 = PathArgument(),
992 const PathArgument& a4 = PathArgument(),
993 const PathArgument& a5 = PathArgument());
995 const Value& resolve(const Value& root) const;
996 Value resolve(const Value& root, const Value& defaultValue) const;
997 /// Creates the "path" to access the specified node and returns a reference on
999 Value& make(Value& root) const;
1002 typedef std::vector<const PathArgument*> InArgs;
1003 typedef std::vector<PathArgument> Args;
1005 void makePath(const std::string& path, const InArgs& in);
1006 void addPathInArg(const std::string& path,
1008 InArgs::const_iterator& itInArg,
1009 PathArgument::Kind kind);
1010 void invalidPath(const std::string& path, int location);
1015 /** \brief base class for Value iterators.
1018 class JSON_API ValueIteratorBase {
1020 typedef std::bidirectional_iterator_tag iterator_category;
1021 typedef unsigned int size_t;
1022 typedef int difference_type;
1023 typedef ValueIteratorBase SelfType;
1025 bool operator==(const SelfType& other) const { return isEqual(other); }
1027 bool operator!=(const SelfType& other) const { return !isEqual(other); }
1029 difference_type operator-(const SelfType& other) const {
1030 return other.computeDistance(*this);
1033 /// Return either the index or the member name of the referenced value as a
1037 /// Return the index of the referenced Value, or -1 if it is not an arrayValue.
1040 /// Return the member name of the referenced Value, or "" if it is not an
1042 /// \note Avoid `c_str()` on result, as embedded zeroes are possible.
1043 std::string name() const;
1045 /// Return the member name of the referenced Value. "" if it is not an
1047 /// \deprecated This cannot be used for UTF-8 strings, since there can be embedded nulls.
1048 JSONCPP_DEPRECATED("Use `key = name();` instead.")
1049 char const* memberName() const;
1050 /// Return the member name of the referenced Value, or NULL if it is not an
1052 /// \note Better version than memberName(). Allows embedded nulls.
1053 char const* memberName(char const** end) const;
1056 Value& deref() const;
1062 difference_type computeDistance(const SelfType& other) const;
1064 bool isEqual(const SelfType& other) const;
1066 void copy(const SelfType& other);
1069 Value::ObjectValues::iterator current_;
1070 // Indicates that iterator is for a null value.
1074 // For some reason, BORLAND needs these at the end, rather
1075 // than earlier. No idea why.
1076 ValueIteratorBase();
1077 explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
1080 /** \brief const iterator for object and array value.
1083 class JSON_API ValueConstIterator : public ValueIteratorBase {
1087 typedef const Value value_type;
1088 //typedef unsigned int size_t;
1089 //typedef int difference_type;
1090 typedef const Value& reference;
1091 typedef const Value* pointer;
1092 typedef ValueConstIterator SelfType;
1094 ValueConstIterator();
1097 /*! \internal Use by Value to create an iterator.
1099 explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
1101 SelfType& operator=(const ValueIteratorBase& other);
1103 SelfType operator++(int) {
1104 SelfType temp(*this);
1109 SelfType operator--(int) {
1110 SelfType temp(*this);
1115 SelfType& operator--() {
1120 SelfType& operator++() {
1125 reference operator*() const { return deref(); }
1127 pointer operator->() const { return &deref(); }
1130 /** \brief Iterator for object and array value.
1132 class JSON_API ValueIterator : public ValueIteratorBase {
1136 typedef Value value_type;
1137 typedef unsigned int size_t;
1138 typedef int difference_type;
1139 typedef Value& reference;
1140 typedef Value* pointer;
1141 typedef ValueIterator SelfType;
1144 ValueIterator(const ValueConstIterator& other);
1145 ValueIterator(const ValueIterator& other);
1148 /*! \internal Use by Value to create an iterator.
1150 explicit ValueIterator(const Value::ObjectValues::iterator& current);
1152 SelfType& operator=(const SelfType& other);
1154 SelfType operator++(int) {
1155 SelfType temp(*this);
1160 SelfType operator--(int) {
1161 SelfType temp(*this);
1166 SelfType& operator--() {
1171 SelfType& operator++() {
1176 reference operator*() const { return deref(); }
1178 pointer operator->() const { return &deref(); }
1185 /// Specialize std::swap() for Json::Value.
1187 inline void swap(Json::Value& a, Json::Value& b) { a.swap(b); }
1191 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1192 #pragma warning(pop)
1193 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1195 #endif // CPPTL_JSON_H_INCLUDED
1197 // //////////////////////////////////////////////////////////////////////
1198 // End of content of file: include/json/value.h
1199 // //////////////////////////////////////////////////////////////////////
1206 // //////////////////////////////////////////////////////////////////////
1207 // Beginning of content of file: include/json/reader.h
1208 // //////////////////////////////////////////////////////////////////////
1210 // Copyright 2007-2010 Baptiste Lepilleur
1211 // Distributed under MIT license, or public domain if desired and
1212 // recognized in your jurisdiction.
1213 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1215 #ifndef CPPTL_JSON_READER_H_INCLUDED
1216 #define CPPTL_JSON_READER_H_INCLUDED
1218 #if !defined(JSON_IS_AMALGAMATION)
1219 #include "features.h"
1221 #endif // if !defined(JSON_IS_AMALGAMATION)
1228 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
1230 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1231 #pragma warning(push)
1232 #pragma warning(disable : 4251)
1233 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1237 /** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a
1240 * \deprecated Use CharReader and CharReaderBuilder.
1242 class JSON_API Reader {
1245 typedef const Char* Location;
1247 /** \brief Constructs a Reader allowing all features
1252 /** \brief Constructs a Reader allowing the specified feature set
1255 Reader(const Features& features);
1257 /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1259 * \param document UTF-8 encoded string containing the document to read.
1260 * \param root [out] Contains the root value of the document if it was
1261 * successfully parsed.
1262 * \param collectComments \c true to collect comment and allow writing them
1264 * serialization, \c false to discard comments.
1265 * This parameter is ignored if
1266 * Features::allowComments_
1268 * \return \c true if the document was successfully parsed, \c false if an
1272 parse(const std::string& document, Value& root, bool collectComments = true);
1274 /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1276 * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
1278 * \param endDoc Pointer on the end of the UTF-8 encoded string of the
1280 * Must be >= beginDoc.
1281 * \param root [out] Contains the root value of the document if it was
1282 * successfully parsed.
1283 * \param collectComments \c true to collect comment and allow writing them
1285 * serialization, \c false to discard comments.
1286 * This parameter is ignored if
1287 Features::allowComments_
1289 * \return \c true if the document was successfully parsed, \c false if an
1292 bool parse(const char* beginDoc,
1295 bool collectComments = true);
1297 /// \brief Parse from input stream.
1298 /// \see Json::operator>>(std::istream&, Json::Value&).
1299 bool parse(std::istream& is, Value& root, bool collectComments = true);
1301 /** \brief Returns a user friendly string that list errors in the parsed
1303 * \return Formatted error message with the list of errors with their location
1305 * the parsed document. An empty string is returned if no error
1308 * \deprecated Use getFormattedErrorMessages() instead (typo fix).
1310 JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.")
1311 std::string getFormatedErrorMessages() const;
1313 /** \brief Returns a user friendly string that list errors in the parsed
1315 * \return Formatted error message with the list of errors with their location
1317 * the parsed document. An empty string is returned if no error
1321 std::string getFormattedErrorMessages() const;
1325 tokenEndOfStream = 0,
1335 tokenArraySeparator,
1336 tokenMemberSeparator,
1351 std::string message_;
1355 typedef std::deque<ErrorInfo> Errors;
1357 bool readToken(Token& token);
1359 bool match(Location pattern, int patternLength);
1361 bool readCStyleComment();
1362 bool readCppStyleComment();
1366 bool readObject(Token& token);
1367 bool readArray(Token& token);
1368 bool decodeNumber(Token& token);
1369 bool decodeNumber(Token& token, Value& decoded);
1370 bool decodeString(Token& token);
1371 bool decodeString(Token& token, std::string& decoded);
1372 bool decodeDouble(Token& token);
1373 bool decodeDouble(Token& token, Value& decoded);
1374 bool decodeUnicodeCodePoint(Token& token,
1377 unsigned int& unicode);
1378 bool decodeUnicodeEscapeSequence(Token& token,
1381 unsigned int& unicode);
1382 bool addError(const std::string& message, Token& token, Location extra = 0);
1383 bool recoverFromError(TokenType skipUntilToken);
1384 bool addErrorAndRecover(const std::string& message,
1386 TokenType skipUntilToken);
1387 void skipUntilSpace();
1388 Value& currentValue();
1391 getLocationLineAndColumn(Location location, int& line, int& column) const;
1392 std::string getLocationLineAndColumn(Location location) const;
1393 void addComment(Location begin, Location end, CommentPlacement placement);
1394 void skipCommentTokens(Token& token);
1396 typedef std::stack<Value*> Nodes;
1399 std::string document_;
1403 Location lastValueEnd_;
1405 std::string commentsBefore_;
1407 bool collectComments_;
1410 /** Interface for reading JSON from a char array.
1412 class JSON_API CharReader {
1414 virtual ~CharReader() {}
1415 /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1417 * The document must be a UTF-8 encoded string containing the document to read.
1419 * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
1421 * \param endDoc Pointer on the end of the UTF-8 encoded string of the
1423 * Must be >= beginDoc.
1424 * \param root [out] Contains the root value of the document if it was
1425 * successfully parsed.
1426 * \param errs [out] Formatted error messages (if not NULL)
1427 * a user friendly string that lists errors in the parsed
1429 * \return \c true if the document was successfully parsed, \c false if an
1433 char const* beginDoc, char const* endDoc,
1434 Value* root, std::string* errs) = 0;
1438 virtual ~Factory() {}
1439 /** \brief Allocate a CharReader via operator new().
1440 * \throw std::exception if something goes wrong (e.g. invalid settings)
1442 virtual CharReader* newCharReader() const = 0;
1446 /** \brief Build a CharReader implementation.
1450 using namespace Json;
1451 CharReaderBuilder builder;
1452 builder["collectComments"] = false;
1455 bool ok = parseFromStream(builder, std::cin, &value, &errs);
1458 class JSON_API CharReaderBuilder : public CharReader::Factory {
1460 // Note: We use a Json::Value so that we can add data-members to this class
1461 // without a major version bump.
1462 /** Configuration of this builder.
1463 These are case-sensitive.
1464 Available settings (case-sensitive):
1465 - `"collectComments": false or true`
1466 - true to collect comment and allow writing them
1467 back during serialization, false to discard comments.
1468 This parameter is ignored if allowComments is false.
1469 - `"allowComments": false or true`
1470 - true if comments are allowed.
1471 - `"strictRoot": false or true`
1472 - true if root must be either an array or an object value
1473 - `"allowDroppedNullPlaceholders": false or true`
1474 - true if dropped null placeholders are allowed. (See StreamWriterBuilder.)
1475 - `"allowNumericKeys": false or true`
1476 - true if numeric object keys are allowed.
1477 - `"allowSingleQuotes": false or true`
1478 - true if '' are allowed for strings (both keys and values)
1479 - `"stackLimit": integer`
1480 - Exceeding stackLimit (recursive depth of `readValue()`) will
1482 - This is a security issue (seg-faults caused by deeply nested JSON),
1483 so the default is low.
1484 - `"failIfExtra": false or true`
1485 - If true, `parse()` returns false when extra non-whitespace trails
1486 the JSON value in the input string.
1487 - `"rejectDupKeys": false or true`
1488 - If true, `parse()` returns false when a key is duplicated within an object.
1489 - `"allowSpecialFloats": false or true`
1490 - If true, special float values (NaNs and infinities) are allowed
1491 and their values are lossfree restorable.
1493 You can examine 'settings_` yourself
1494 to see the defaults. You can also write and read them just like any
1498 Json::Value settings_;
1500 CharReaderBuilder();
1501 virtual ~CharReaderBuilder();
1503 virtual CharReader* newCharReader() const;
1505 /** \return true if 'settings' are legal and consistent;
1506 * otherwise, indicate bad settings via 'invalid'.
1508 bool validate(Json::Value* invalid) const;
1510 /** A simple way to update a specific setting.
1512 Value& operator[](std::string key);
1514 /** Called by ctor, but you can use this to reset settings_.
1515 * \pre 'settings' != NULL (but Json::null is fine)
1517 * \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults
1519 static void setDefaults(Json::Value* settings);
1520 /** Same as old Features::strictMode().
1521 * \pre 'settings' != NULL (but Json::null is fine)
1523 * \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode
1525 static void strictMode(Json::Value* settings);
1528 /** Consume entire stream and use its begin/end.
1529 * Someday we might have a real StreamReader, but for now this
1532 bool JSON_API parseFromStream(
1533 CharReader::Factory const&,
1535 Value* root, std::string* errs);
1537 /** \brief Read from 'sin' into 'root'.
1539 Always keep comments from the input JSON.
1541 This can be used to read a file into a particular sub-object.
1545 cin >> root["dir"]["file"];
1553 // The input stream JSON would be nested here.
1558 \throw std::exception on parse error.
1559 \see Json::operator<<()
1561 JSON_API std::istream& operator>>(std::istream&, Value&);
1565 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1566 #pragma warning(pop)
1567 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1569 #endif // CPPTL_JSON_READER_H_INCLUDED
1571 // //////////////////////////////////////////////////////////////////////
1572 // End of content of file: include/json/reader.h
1573 // //////////////////////////////////////////////////////////////////////
1580 // //////////////////////////////////////////////////////////////////////
1581 // Beginning of content of file: include/json/writer.h
1582 // //////////////////////////////////////////////////////////////////////
1584 // Copyright 2007-2010 Baptiste Lepilleur
1585 // Distributed under MIT license, or public domain if desired and
1586 // recognized in your jurisdiction.
1587 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1589 #ifndef JSON_WRITER_H_INCLUDED
1590 #define JSON_WRITER_H_INCLUDED
1592 #if !defined(JSON_IS_AMALGAMATION)
1594 #endif // if !defined(JSON_IS_AMALGAMATION)
1599 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
1601 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1602 #pragma warning(push)
1603 #pragma warning(disable : 4251)
1604 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1614 using namespace Json;
1615 void writeToStdout(StreamWriter::Factory const& factory, Value const& value) {
1616 std::unique_ptr<StreamWriter> const writer(
1617 factory.newStreamWriter());
1618 writer->write(value, &std::cout);
1619 std::cout << std::endl; // add lf and flush
1623 class JSON_API StreamWriter {
1625 std::ostream* sout_; // not owned; will not delete
1628 virtual ~StreamWriter();
1629 /** Write Value into document as configured in sub-class.
1630 Do not take ownership of sout, but maintain a reference during function.
1632 \return zero on success (For now, we always return zero, so check the stream instead.)
1633 \throw std::exception possibly, depending on configuration
1635 virtual int write(Value const& root, std::ostream* sout) = 0;
1637 /** \brief A simple abstract factory.
1639 class JSON_API Factory {
1642 /** \brief Allocate a CharReader via operator new().
1643 * \throw std::exception if something goes wrong (e.g. invalid settings)
1645 virtual StreamWriter* newStreamWriter() const = 0;
1649 /** \brief Write into stringstream, then return string, for convenience.
1650 * A StreamWriter will be created from the factory, used, and then deleted.
1652 std::string JSON_API writeString(StreamWriter::Factory const& factory, Value const& root);
1655 /** \brief Build a StreamWriter implementation.
1659 using namespace Json;
1661 StreamWriterBuilder builder;
1662 builder["commentStyle"] = "None";
1663 builder["indentation"] = " "; // or whatever you like
1664 std::unique_ptr<Json::StreamWriter> writer(
1665 builder.newStreamWriter());
1666 writer->write(value, &std::cout);
1667 std::cout << std::endl; // add lf and flush
1670 class JSON_API StreamWriterBuilder : public StreamWriter::Factory {
1672 // Note: We use a Json::Value so that we can add data-members to this class
1673 // without a major version bump.
1674 /** Configuration of this builder.
1675 Available settings (case-sensitive):
1676 - "commentStyle": "None" or "All"
1677 - "indentation": "<anything>"
1678 - "enableYAMLCompatibility": false or true
1679 - slightly change the whitespace around colons
1680 - "dropNullPlaceholders": false or true
1681 - Drop the "null" string from the writer's output for nullValues.
1682 Strictly speaking, this is not valid JSON. But when the output is being
1683 fed to a browser's Javascript, it makes for smaller output and the
1684 browser can handle the output just fine.
1685 - "useSpecialFloats": false or true
1686 - If true, outputs non-finite floating point values in the following way:
1687 NaN values as "NaN", positive infinity as "Infinity", and negative infinity
1690 You can examine 'settings_` yourself
1691 to see the defaults. You can also write and read them just like any
1695 Json::Value settings_;
1697 StreamWriterBuilder();
1698 virtual ~StreamWriterBuilder();
1701 * \throw std::exception if something goes wrong (e.g. invalid settings)
1703 virtual StreamWriter* newStreamWriter() const;
1705 /** \return true if 'settings' are legal and consistent;
1706 * otherwise, indicate bad settings via 'invalid'.
1708 bool validate(Json::Value* invalid) const;
1709 /** A simple way to update a specific setting.
1711 Value& operator[](std::string key);
1713 /** Called by ctor, but you can use this to reset settings_.
1714 * \pre 'settings' != NULL (but Json::null is fine)
1716 * \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults
1718 static void setDefaults(Json::Value* settings);
1721 /** \brief Abstract class for writers.
1722 * \deprecated Use StreamWriter. (And really, this is an implementation detail.)
1724 class JSON_API Writer {
1728 virtual std::string write(const Value& root) = 0;
1731 /** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format
1732 *without formatting (not human friendly).
1734 * The JSON document is written in a single line. It is not intended for 'human'
1736 * but may be usefull to support feature such as RPC where bandwith is limited.
1738 * \deprecated Use StreamWriterBuilder.
1740 class JSON_API FastWriter : public Writer {
1744 virtual ~FastWriter() {}
1746 void enableYAMLCompatibility();
1748 public: // overridden from Writer
1749 virtual std::string write(const Value& root);
1752 void writeValue(const Value& value);
1754 std::string document_;
1755 bool yamlCompatiblityEnabled_;
1758 /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
1759 *human friendly way.
1761 * The rules for line break and indent are as follow:
1763 * - if empty then print {} without indent and line break
1764 * - if not empty the print '{', line break & indent, print one value per
1766 * and then unindent and line break and print '}'.
1768 * - if empty then print [] without indent and line break
1769 * - if the array contains no object value, empty array or some other value
1771 * and all the values fit on one lines, then print the array on a single
1773 * - otherwise, it the values do not fit on one line, or the array contains
1774 * object or non empty array, then print one value per line.
1776 * If the Value have comments then they are outputed according to their
1779 * \sa Reader, Value, Value::setComment()
1780 * \deprecated Use StreamWriterBuilder.
1782 class JSON_API StyledWriter : public Writer {
1785 virtual ~StyledWriter() {}
1787 public: // overridden from Writer
1788 /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
1789 * \param root Value to serialize.
1790 * \return String containing the JSON document that represents the root value.
1792 virtual std::string write(const Value& root);
1795 void writeValue(const Value& value);
1796 void writeArrayValue(const Value& value);
1797 bool isMultineArray(const Value& value);
1798 void pushValue(const std::string& value);
1800 void writeWithIndent(const std::string& value);
1803 void writeCommentBeforeValue(const Value& root);
1804 void writeCommentAfterValueOnSameLine(const Value& root);
1805 bool hasCommentForValue(const Value& value);
1806 static std::string normalizeEOL(const std::string& text);
1808 typedef std::vector<std::string> ChildValues;
1810 ChildValues childValues_;
1811 std::string document_;
1812 std::string indentString_;
1815 bool addChildValues_;
1818 /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
1820 to a stream rather than to a string.
1822 * The rules for line break and indent are as follow:
1824 * - if empty then print {} without indent and line break
1825 * - if not empty the print '{', line break & indent, print one value per
1827 * and then unindent and line break and print '}'.
1829 * - if empty then print [] without indent and line break
1830 * - if the array contains no object value, empty array or some other value
1832 * and all the values fit on one lines, then print the array on a single
1834 * - otherwise, it the values do not fit on one line, or the array contains
1835 * object or non empty array, then print one value per line.
1837 * If the Value have comments then they are outputed according to their
1840 * \param indentation Each level will be indented by this amount extra.
1841 * \sa Reader, Value, Value::setComment()
1842 * \deprecated Use StreamWriterBuilder.
1844 class JSON_API StyledStreamWriter {
1846 StyledStreamWriter(std::string indentation = "\t");
1847 ~StyledStreamWriter() {}
1850 /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
1851 * \param out Stream to write to. (Can be ostringstream, e.g.)
1852 * \param root Value to serialize.
1853 * \note There is no point in deriving from Writer, since write() should not
1856 void write(std::ostream& out, const Value& root);
1859 void writeValue(const Value& value);
1860 void writeArrayValue(const Value& value);
1861 bool isMultineArray(const Value& value);
1862 void pushValue(const std::string& value);
1864 void writeWithIndent(const std::string& value);
1867 void writeCommentBeforeValue(const Value& root);
1868 void writeCommentAfterValueOnSameLine(const Value& root);
1869 bool hasCommentForValue(const Value& value);
1870 static std::string normalizeEOL(const std::string& text);
1872 typedef std::vector<std::string> ChildValues;
1874 ChildValues childValues_;
1875 std::ostream* document_;
1876 std::string indentString_;
1878 std::string indentation_;
1879 bool addChildValues_ : 1;
1883 #if defined(JSON_HAS_INT64)
1884 std::string JSON_API valueToString(Int value);
1885 std::string JSON_API valueToString(UInt value);
1886 #endif // if defined(JSON_HAS_INT64)
1887 std::string JSON_API valueToString(LargestInt value);
1888 std::string JSON_API valueToString(LargestUInt value);
1889 std::string JSON_API valueToString(double value);
1890 std::string JSON_API valueToString(bool value);
1891 std::string JSON_API valueToQuotedString(const char* value);
1893 /// \brief Output using the StyledStreamWriter.
1894 /// \see Json::operator>>()
1895 JSON_API std::ostream& operator<<(std::ostream&, const Value& root);
1899 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1900 #pragma warning(pop)
1901 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1903 #endif // JSON_WRITER_H_INCLUDED
1905 // //////////////////////////////////////////////////////////////////////
1906 // End of content of file: include/json/writer.h
1907 // //////////////////////////////////////////////////////////////////////
1914 // //////////////////////////////////////////////////////////////////////
1915 // Beginning of content of file: include/json/assertions.h
1916 // //////////////////////////////////////////////////////////////////////
1918 // Copyright 2007-2010 Baptiste Lepilleur
1919 // Distributed under MIT license, or public domain if desired and
1920 // recognized in your jurisdiction.
1921 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1923 #ifndef CPPTL_JSON_ASSERTIONS_H_INCLUDED
1924 #define CPPTL_JSON_ASSERTIONS_H_INCLUDED
1929 #if !defined(JSON_IS_AMALGAMATION)
1931 #endif // if !defined(JSON_IS_AMALGAMATION)
1933 /** It should not be possible for a maliciously designed file to
1934 * cause an abort() or seg-fault, so these macros are used only
1935 * for pre-condition violations and internal logic errors.
1937 #if JSON_USE_EXCEPTION
1939 // @todo <= add detail about condition in exception
1940 # define JSON_ASSERT(condition) \
1941 {if (!(condition)) {Json::throwLogicError( "assert json failed" );}}
1943 # define JSON_FAIL_MESSAGE(message) \
1945 std::ostringstream oss; oss << message; \
1946 Json::throwLogicError(oss.str()); \
1950 #else // JSON_USE_EXCEPTION
1952 # define JSON_ASSERT(condition) assert(condition)
1954 // The call to assert() will show the failure message in debug builds. In
1955 // release builds we abort, for a core-dump or debugger.
1956 # define JSON_FAIL_MESSAGE(message) \
1958 std::ostringstream oss; oss << message; \
1959 assert(false && oss.str().c_str()); \
1966 #define JSON_ASSERT_MESSAGE(condition, message) \
1967 if (!(condition)) { \
1968 JSON_FAIL_MESSAGE(message); \
1971 #endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED
1973 // //////////////////////////////////////////////////////////////////////
1974 // End of content of file: include/json/assertions.h
1975 // //////////////////////////////////////////////////////////////////////
1981 #endif //ifndef JSON_AMALGATED_H_INCLUDED