• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
5 #ifndef BASE_JSON_JSON_WRITER_H_
6 #define BASE_JSON_JSON_WRITER_H_
7 
8 #include <stddef.h>
9 
10 #include <string>
11 
12 #include "base/base_export.h"
13 #include "base/macros.h"
14 
15 namespace base {
16 
17 class Value;
18 
19 class BASE_EXPORT JSONWriter {
20  public:
21   enum Options {
22     // This option instructs the writer that if a Binary value is encountered,
23     // the value (and key if within a dictionary) will be omitted from the
24     // output, and success will be returned. Otherwise, if a binary value is
25     // encountered, failure will be returned.
26     OPTIONS_OMIT_BINARY_VALUES = 1 << 0,
27 
28     // This option instructs the writer to write doubles that have no fractional
29     // part as a normal integer (i.e., without using exponential notation
30     // or appending a '.0') as long as the value is within the range of a
31     // 64-bit int.
32     OPTIONS_OMIT_DOUBLE_TYPE_PRESERVATION = 1 << 1,
33 
34     // Return a slightly nicer formatted json string (pads with whitespace to
35     // help with readability).
36     OPTIONS_PRETTY_PRINT = 1 << 2,
37   };
38 
39   // Given a root node, generates a JSON string and puts it into |json|.
40   // The output string is overwritten and not appended.
41   //
42   // TODO(tc): Should we generate json if it would be invalid json (e.g.,
43   // |node| is not a DictionaryValue/ListValue or if there are inf/-inf float
44   // values)? Return true on success and false on failure.
45   static bool Write(const Value& node, std::string* json);
46 
47   // Same as above but with |options| which is a bunch of JSONWriter::Options
48   // bitwise ORed together. Return true on success and false on failure.
49   static bool WriteWithOptions(const Value& node,
50                                int options,
51                                std::string* json);
52 
53  private:
54   JSONWriter(int options, std::string* json);
55 
56   // Called recursively to build the JSON string. When completed,
57   // |json_string_| will contain the JSON.
58   bool BuildJSONString(const Value& node, size_t depth);
59 
60   // Adds space to json_string_ for the indent level.
61   void IndentLine(size_t depth);
62 
63   bool omit_binary_values_;
64   bool omit_double_type_preservation_;
65   bool pretty_print_;
66 
67   // Where we write JSON data as we generate it.
68   std::string* json_string_;
69 
70   DISALLOW_COPY_AND_ASSIGN(JSONWriter);
71 };
72 
73 }  // namespace base
74 
75 #endif  // BASE_JSON_JSON_WRITER_H_
76