• 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 namespace base {
13 
14 class Value;
15 
16 class JSONWriter {
17  public:
18   enum Options {
19     // This option instructs the writer that if a Binary value is encountered,
20     // the value (and key if within a dictionary) will be omitted from the
21     // output, and success will be returned. Otherwise, if a binary value is
22     // encountered, failure will be returned.
23     OPTIONS_OMIT_BINARY_VALUES = 1 << 0,
24 
25     // Return a slightly nicer formatted json string (pads with whitespace to
26     // help with readability).
27     OPTIONS_PRETTY_PRINT = 1 << 2,
28   };
29 
30   // Given a root node, generates a JSON string and puts it into |json|.
31   // The output string is overwritten and not appended.
32   //
33   // TODO(tc): Should we generate json if it would be invalid json (e.g.,
34   // |node| is not a DictionaryValue/ListValue or if there are inf/-inf float
35   // values)? Return true on success and false on failure.
36   static bool Write(const Value& node, std::string* json);
37 
38   // Same as above but with |options| which is a bunch of JSONWriter::Options
39   // bitwise ORed together. Return true on success and false on failure.
40   static bool WriteWithOptions(const Value& node,
41                                int options,
42                                std::string* json);
43 
44  private:
45   JSONWriter(int options, std::string* json);
46 
47   // Called recursively to build the JSON string. When completed,
48   // |json_string_| will contain the JSON.
49   bool BuildJSONString(const Value& node, size_t depth);
50 
51   // Adds space to json_string_ for the indent level.
52   void IndentLine(size_t depth);
53 
54   bool omit_binary_values_;
55   bool pretty_print_;
56 
57   // Where we write JSON data as we generate it.
58   std::string* json_string_;
59 
60   JSONWriter(const JSONWriter&) = delete;
61   JSONWriter& operator=(const JSONWriter&) = delete;
62 };
63 
64 }  // namespace base
65 
66 #endif  // BASE_JSON_JSON_WRITER_H_
67