1 // Copyright (c) 2006-2008 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.
5 #include "base/json/string_escape.h"
9 #include "base/stringprintf.h"
10 #include "base/string_util.h"
16 // Try to escape |c| as a "SingleEscapeCharacter" (\n, etc). If successful,
17 // returns true and appends the escape sequence to |dst|. This isn't required
18 // by the spec, but it's more readable by humans than the \uXXXX alternatives.
19 template<typename CHAR
>
20 static bool JsonSingleEscapeChar(const CHAR c
, std::string
* dst
) {
21 // WARNING: if you add a new case here, you need to update the reader as well.
22 // Note: \v is in the reader, but not here since the JSON spec doesn't
53 void JsonDoubleQuoteT(const STR
& str
,
59 for (typename
STR::const_iterator it
= str
.begin(); it
!= str
.end(); ++it
) {
60 typename ToUnsigned
<typename
STR::value_type
>::Unsigned c
= *it
;
61 if (!JsonSingleEscapeChar(c
, dst
)) {
62 if (c
< 32 || c
> 126 || c
== '<' || c
== '>') {
63 // 1. Escaping <, > to prevent script execution.
64 // 2. Technically, we could also pass through c > 126 as UTF8, but this
65 // is also optional. It would also be a pain to implement here.
66 unsigned int as_uint
= static_cast<unsigned int>(c
);
67 base::StringAppendF(dst
, "\\u%04X", as_uint
);
69 unsigned char ascii
= static_cast<unsigned char>(*it
);
70 dst
->push_back(ascii
);
81 void JsonDoubleQuote(const std::string
& str
,
84 JsonDoubleQuoteT(str
, put_in_quotes
, dst
);
87 std::string
GetDoubleQuotedJson(const std::string
& str
) {
89 JsonDoubleQuote(str
, true, &dst
);
93 void JsonDoubleQuote(const string16
& str
,
96 JsonDoubleQuoteT(str
, put_in_quotes
, dst
);
99 std::string
GetDoubleQuotedJson(const string16
& str
) {
101 JsonDoubleQuote(str
, true, &dst
);