json_writer.cc 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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.
  4. #include "base/json/json_writer.h"
  5. #include <stdint.h>
  6. #include <cmath>
  7. #include <limits>
  8. #include "base/json/string_escape.h"
  9. #include "base/logging.h"
  10. #include "base/notreached.h"
  11. #include "base/numerics/safe_conversions.h"
  12. #include "base/strings/string_number_conversions.h"
  13. #include "base/strings/utf_string_conversions.h"
  14. #include "base/values.h"
  15. #include "build/build_config.h"
  16. namespace base {
  17. #if BUILDFLAG(IS_WIN)
  18. const char kPrettyPrintLineEnding[] = "\r\n";
  19. #else
  20. const char kPrettyPrintLineEnding[] = "\n";
  21. #endif
  22. // static
  23. bool JSONWriter::Write(ValueView node, std::string* json, size_t max_depth) {
  24. return WriteWithOptions(node, 0, json, max_depth);
  25. }
  26. // static
  27. bool JSONWriter::WriteWithOptions(ValueView node,
  28. int options,
  29. std::string* json,
  30. size_t max_depth) {
  31. json->clear();
  32. // Is there a better way to estimate the size of the output?
  33. if (json->capacity() < 1024)
  34. json->reserve(1024);
  35. JSONWriter writer(options, json, max_depth);
  36. bool result = node.Visit([&writer](const auto& member) {
  37. return writer.BuildJSONString(member, 0);
  38. });
  39. if (options & OPTIONS_PRETTY_PRINT)
  40. json->append(kPrettyPrintLineEnding);
  41. return result;
  42. }
  43. JSONWriter::JSONWriter(int options, std::string* json, size_t max_depth)
  44. : omit_binary_values_((options & OPTIONS_OMIT_BINARY_VALUES) != 0),
  45. omit_double_type_preservation_(
  46. (options & OPTIONS_OMIT_DOUBLE_TYPE_PRESERVATION) != 0),
  47. pretty_print_((options & OPTIONS_PRETTY_PRINT) != 0),
  48. json_string_(json),
  49. max_depth_(max_depth),
  50. stack_depth_(0) {
  51. DCHECK(json);
  52. CHECK_LE(max_depth, internal::kAbsoluteMaxDepth);
  53. }
  54. bool JSONWriter::BuildJSONString(absl::monostate node, size_t depth) {
  55. json_string_->append("null");
  56. return true;
  57. }
  58. bool JSONWriter::BuildJSONString(bool node, size_t depth) {
  59. json_string_->append(node ? "true" : "false");
  60. return true;
  61. }
  62. bool JSONWriter::BuildJSONString(int node, size_t depth) {
  63. json_string_->append(NumberToString(node));
  64. return true;
  65. }
  66. bool JSONWriter::BuildJSONString(double node, size_t depth) {
  67. if (omit_double_type_preservation_ &&
  68. IsValueInRangeForNumericType<int64_t>(node) && std::floor(node) == node) {
  69. json_string_->append(NumberToString(static_cast<int64_t>(node)));
  70. return true;
  71. }
  72. std::string real = NumberToString(node);
  73. // Ensure that the number has a .0 if there's no decimal or 'e'. This
  74. // makes sure that when we read the JSON back, it's interpreted as a
  75. // real rather than an int.
  76. if (real.find_first_of(".eE") == std::string::npos)
  77. real.append(".0");
  78. // The JSON spec requires that non-integer values in the range (-1,1)
  79. // have a zero before the decimal point - ".52" is not valid, "0.52" is.
  80. if (real[0] == '.') {
  81. real.insert(0, 1, '0');
  82. } else if (real.length() > 1 && real[0] == '-' && real[1] == '.') {
  83. // "-.1" bad "-0.1" good
  84. real.insert(1, 1, '0');
  85. }
  86. json_string_->append(real);
  87. return true;
  88. }
  89. bool JSONWriter::BuildJSONString(StringPiece node, size_t depth) {
  90. EscapeJSONString(node, true, json_string_);
  91. return true;
  92. }
  93. bool JSONWriter::BuildJSONString(const Value::BlobStorage& node, size_t depth) {
  94. // Successful only if we're allowed to omit it.
  95. DLOG_IF(ERROR, !omit_binary_values_) << "Cannot serialize binary value.";
  96. return omit_binary_values_;
  97. }
  98. bool JSONWriter::BuildJSONString(const Value::Dict& node, size_t depth) {
  99. internal::StackMarker depth_check(max_depth_, &stack_depth_);
  100. if (depth_check.IsTooDeep())
  101. return false;
  102. json_string_->push_back('{');
  103. if (pretty_print_)
  104. json_string_->append(kPrettyPrintLineEnding);
  105. bool first_value_has_been_output = false;
  106. bool result = true;
  107. for (const auto [key, value] : node) {
  108. if (omit_binary_values_ && value.type() == Value::Type::BINARY)
  109. continue;
  110. if (first_value_has_been_output) {
  111. json_string_->push_back(',');
  112. if (pretty_print_)
  113. json_string_->append(kPrettyPrintLineEnding);
  114. }
  115. if (pretty_print_)
  116. IndentLine(depth + 1U);
  117. EscapeJSONString(key, true, json_string_);
  118. json_string_->push_back(':');
  119. if (pretty_print_)
  120. json_string_->push_back(' ');
  121. result &= value.Visit([this, depth = depth + 1](const auto& member) {
  122. return BuildJSONString(member, depth);
  123. });
  124. first_value_has_been_output = true;
  125. }
  126. if (pretty_print_) {
  127. if (first_value_has_been_output)
  128. json_string_->append(kPrettyPrintLineEnding);
  129. IndentLine(depth);
  130. }
  131. json_string_->push_back('}');
  132. return result;
  133. }
  134. bool JSONWriter::BuildJSONString(const Value::List& node, size_t depth) {
  135. internal::StackMarker depth_check(max_depth_, &stack_depth_);
  136. if (depth_check.IsTooDeep())
  137. return false;
  138. json_string_->push_back('[');
  139. if (pretty_print_)
  140. json_string_->push_back(' ');
  141. bool first_value_has_been_output = false;
  142. bool result = true;
  143. for (const auto& value : node) {
  144. if (omit_binary_values_ && value.type() == Value::Type::BINARY)
  145. continue;
  146. if (first_value_has_been_output) {
  147. json_string_->push_back(',');
  148. if (pretty_print_)
  149. json_string_->push_back(' ');
  150. }
  151. result &= value.Visit([this, depth](const auto& member) {
  152. return BuildJSONString(member, depth);
  153. });
  154. first_value_has_been_output = true;
  155. }
  156. if (pretty_print_)
  157. json_string_->push_back(' ');
  158. json_string_->push_back(']');
  159. return result;
  160. }
  161. void JSONWriter::IndentLine(size_t depth) {
  162. json_string_->append(depth * 3U, ' ');
  163. }
  164. } // namespace base