1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/json/json_writer.h"
9 #include "base/json/string_escape.h"
10 #include "base/logging.h"
11 #include "base/strings/string_number_conversions.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "base/values.h"
18 const char kPrettyPrintLineEnding
[] = "\r\n";
20 const char kPrettyPrintLineEnding
[] = "\n";
24 bool JSONWriter::Write(const Value
& node
, std::string
* json
) {
25 return WriteWithOptions(node
, 0, json
);
29 bool JSONWriter::WriteWithOptions(const Value
& node
,
33 // Is there a better way to estimate the size of the output?
36 JSONWriter
writer(options
, json
);
37 bool result
= writer
.BuildJSONString(node
, 0U);
39 if (options
& OPTIONS_PRETTY_PRINT
)
40 json
->append(kPrettyPrintLineEnding
);
45 JSONWriter::JSONWriter(int options
, std::string
* json
)
46 : omit_binary_values_((options
& OPTIONS_OMIT_BINARY_VALUES
) != 0),
47 omit_double_type_preservation_(
48 (options
& OPTIONS_OMIT_DOUBLE_TYPE_PRESERVATION
) != 0),
49 pretty_print_((options
& OPTIONS_PRETTY_PRINT
) != 0),
54 bool JSONWriter::BuildJSONString(const Value
& node
, size_t depth
) {
55 switch (node
.GetType()) {
56 case Value::TYPE_NULL
: {
57 json_string_
->append("null");
61 case Value::TYPE_BOOLEAN
: {
63 bool result
= node
.GetAsBoolean(&value
);
65 json_string_
->append(value
? "true" : "false");
69 case Value::TYPE_INTEGER
: {
71 bool result
= node
.GetAsInteger(&value
);
73 json_string_
->append(IntToString(value
));
77 case Value::TYPE_DOUBLE
: {
79 bool result
= node
.GetAsDouble(&value
);
81 if (omit_double_type_preservation_
&&
84 std::floor(value
) == value
) {
85 json_string_
->append(Int64ToString(static_cast<int64
>(value
)));
88 std::string real
= DoubleToString(value
);
89 // Ensure that the number has a .0 if there's no decimal or 'e'. This
90 // makes sure that when we read the JSON back, it's interpreted as a
91 // real rather than an int.
92 if (real
.find('.') == std::string::npos
&&
93 real
.find('e') == std::string::npos
&&
94 real
.find('E') == std::string::npos
) {
97 // The JSON spec requires that non-integer values in the range (-1,1)
98 // have a zero before the decimal point - ".52" is not valid, "0.52" is.
100 real
.insert(static_cast<size_t>(0), static_cast<size_t>(1), '0');
101 } else if (real
.length() > 1 && real
[0] == '-' && real
[1] == '.') {
102 // "-.1" bad "-0.1" good
103 real
.insert(static_cast<size_t>(1), static_cast<size_t>(1), '0');
105 json_string_
->append(real
);
109 case Value::TYPE_STRING
: {
111 bool result
= node
.GetAsString(&value
);
113 EscapeJSONString(value
, true, json_string_
);
117 case Value::TYPE_LIST
: {
118 json_string_
->push_back('[');
120 json_string_
->push_back(' ');
122 const ListValue
* list
= NULL
;
123 bool first_value_has_been_output
= false;
124 bool result
= node
.GetAsList(&list
);
126 for (ListValue::const_iterator it
= list
->begin(); it
!= list
->end();
128 const Value
* value
= *it
;
129 if (omit_binary_values_
&& value
->GetType() == Value::TYPE_BINARY
)
132 if (first_value_has_been_output
) {
133 json_string_
->push_back(',');
135 json_string_
->push_back(' ');
138 if (!BuildJSONString(*value
, depth
))
141 first_value_has_been_output
= true;
145 json_string_
->push_back(' ');
146 json_string_
->push_back(']');
150 case Value::TYPE_DICTIONARY
: {
151 json_string_
->push_back('{');
153 json_string_
->append(kPrettyPrintLineEnding
);
155 const DictionaryValue
* dict
= NULL
;
156 bool first_value_has_been_output
= false;
157 bool result
= node
.GetAsDictionary(&dict
);
159 for (DictionaryValue::Iterator
itr(*dict
); !itr
.IsAtEnd();
161 if (omit_binary_values_
&&
162 itr
.value().GetType() == Value::TYPE_BINARY
) {
166 if (first_value_has_been_output
) {
167 json_string_
->push_back(',');
169 json_string_
->append(kPrettyPrintLineEnding
);
173 IndentLine(depth
+ 1U);
175 EscapeJSONString(itr
.key(), true, json_string_
);
176 json_string_
->push_back(':');
178 json_string_
->push_back(' ');
180 if (!BuildJSONString(itr
.value(), depth
+ 1U))
183 first_value_has_been_output
= true;
187 json_string_
->append(kPrettyPrintLineEnding
);
191 json_string_
->push_back('}');
195 case Value::TYPE_BINARY
:
196 // Successful only if we're allowed to omit it.
197 DLOG_IF(ERROR
, !omit_binary_values_
) << "Cannot serialize binary value.";
198 return omit_binary_values_
;
204 void JSONWriter::IndentLine(size_t depth
) {
205 json_string_
->append(depth
* 3U, ' ');