cprover
json.cpp
Go to the documentation of this file.
1 /*******************************************************************\
2 
3 Module:
4 
5 Author: Daniel Kroening, kroening@kroening.com
6 
7 \*******************************************************************/
8 
9 #include "json.h"
10 
11 #include <ostream>
12 
14 
15 void jsont::escape_string(const std::string &src, std::ostream &out)
16 {
17  for(const auto &ch : src)
18  {
19  switch(ch)
20  {
21  case '\\':
22  case '"':
23  out << '\\';
24  out << ch;
25  break;
26 
27  case '\b':
28  out << "\\b";
29  break;
30 
31  case '\f':
32  out << "\\f";
33  break;
34 
35  case '\n':
36  out << "\\n";
37  break;
38 
39  case '\r':
40  out << "\\r";
41  break;
42 
43  case '\t':
44  out << "\\t";
45  break;
46 
47  default:
48  out << ch;
49  }
50  }
51 }
52 
53 void jsont::output_rec(std::ostream &out, unsigned indent) const
54 {
55  switch(kind)
56  {
57  case kindt::J_STRING:
58  out << '"';
59  escape_string(value, out);
60  out << '"';
61  break;
62 
63  case kindt::J_NUMBER:
64  out << value;
65  break;
66 
67  case kindt::J_OBJECT:
68  out << '{';
69  for(objectt::const_iterator o_it=object.begin();
70  o_it!=object.end();
71  o_it++)
72  {
73  if(o_it!=object.begin())
74  out << ',';
75 
76  out << '\n';
77 
78  out << std::string((indent+1)*2, ' ');
79 
80  out << '"';
81  escape_string(o_it->first, out);
82  out << '"';
83  out << ": ";
84  o_it->second.output_rec(out, indent+1);
85  }
86  if(!object.empty())
87  {
88  out << '\n';
89  out << std::string(indent*2, ' ');
90  }
91  out << '}';
92  break;
93 
94  case kindt::J_ARRAY:
95  out << '[';
96 
97  if(array.empty())
98  out << ' ';
99  else
100  {
101  for(arrayt::const_iterator a_it=array.begin();
102  a_it!=array.end();
103  a_it++)
104  {
105  if(a_it!=array.begin())
106  out << ',';
107 
108  if(a_it->is_object())
109  {
110  out << '\n';
111  out << std::string((indent+1)*2, ' ');
112  }
113  else
114  out << ' ';
115 
116  a_it->output_rec(out, indent+1);
117  }
118 
119  if(array.back().is_object())
120  out << '\n' << std::string(indent*2, ' ');
121  else
122  out << ' ';
123  }
124 
125  out << ']';
126  break;
127 
128  case kindt::J_TRUE: out << "true"; break;
129 
130  case kindt::J_FALSE: out << "false"; break;
131 
132  case kindt::J_NULL: out << "null"; break;
133  }
134 }
135 
136 void jsont::swap(jsont &other)
137 {
138  std::swap(other.kind, kind);
139  other.array.swap(array);
140  other.object.swap(object);
141  other.value.swap(value);
142 }
Definition: json.h:21
static void escape_string(const std::string &, std::ostream &)
Definition: json.cpp:15
void output_rec(std::ostream &, unsigned indent) const
Definition: json.cpp:53
objectt object
Definition: json.h:129
std::string value
Definition: json.h:131
static const jsont null_json_object
Definition: json.h:113
void swap(jsont &other)
Definition: json.cpp:136
kindt kind
Definition: json.h:35
arrayt array
Definition: json.h:126