Ninja
json.cc
Go to the documentation of this file.
1 // Copyright 2021 Google Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "json.h"
16 
17 #include <cstdio>
18 #include <string>
19 
20 std::string EncodeJSONString(const std::string& in) {
21  static const char* hex_digits = "0123456789abcdef";
22  std::string out;
23  out.reserve(in.length() * 1.2);
24  for (std::string::const_iterator it = in.begin(); it != in.end(); ++it) {
25  char c = *it;
26  if (c == '\b')
27  out += "\\b";
28  else if (c == '\f')
29  out += "\\f";
30  else if (c == '\n')
31  out += "\\n";
32  else if (c == '\r')
33  out += "\\r";
34  else if (c == '\t')
35  out += "\\t";
36  else if (0x0 <= c && c < 0x20) {
37  out += "\\u00";
38  out += hex_digits[c >> 4];
39  out += hex_digits[c & 0xf];
40  } else if (c == '\\')
41  out += "\\\\";
42  else if (c == '\"')
43  out += "\\\"";
44  else
45  out += c;
46  }
47  return out;
48 }
49 
50 void PrintJSONString(const std::string& in) {
51  std::string out = EncodeJSONString(in);
52  fwrite(out.c_str(), 1, out.length(), stdout);
53 }
void PrintJSONString(const std::string &in)
Definition: json.cc:50
std::string EncodeJSONString(const std::string &in)
Definition: json.cc:20