1 // Copyright (c) 2011 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 // This file defines utility functions for escaping strings suitable for JSON. 6 7 #ifndef BASE_JSON_STRING_ESCAPE_H_ 8 #define BASE_JSON_STRING_ESCAPE_H_ 9 10 #include <string> 11 #include <string_view> 12 13 namespace base { 14 15 // Appends to |dest| an escaped version of |str|. Valid UTF-8 code units and 16 // characters will pass through from the input to the output. Invalid code 17 // units and characters will be replaced with the U+FFFD replacement character. 18 // This function returns true if no replacement was necessary and false if 19 // there was a lossy replacement. On return, |dest| will contain a valid UTF-8 20 // JSON string. 21 // 22 // Non-printing control characters will be escaped as \uXXXX sequences for 23 // readability. 24 // 25 // If |put_in_quotes| is true, then a leading and trailing double-quote mark 26 // will be appended to |dest| as well. 27 bool EscapeJSONString(std::string_view str, 28 bool put_in_quotes, 29 std::string* dest); 30 31 // Performs a similar function to the UTF-8 std::string_view version above, 32 // converting UTF-16 code units to UTF-8 code units and escaping non-printing 33 // control characters. On return, |dest| will contain a valid UTF-8 JSON string. 34 bool EscapeJSONString(std::u16string_view str, 35 bool put_in_quotes, 36 std::string* dest); 37 38 // Helper functions that wrap the above two functions but return the value 39 // instead of appending. |put_in_quotes| is always true. 40 std::string GetQuotedJSONString(std::string_view str); 41 std::string GetQuotedJSONString(std::u16string_view str); 42 43 // Given an arbitrary byte string |str|, this will escape all non-ASCII bytes 44 // as \uXXXX escape sequences. This function is *NOT* meant to be used with 45 // Unicode strings and does not validate |str| as one. 46 // 47 // CAVEAT CALLER: The output of this function may not be valid JSON, since 48 // JSON requires escape sequences to be valid UTF-16 code units. This output 49 // will be mangled if passed to to the base::JSONReader, since the reader will 50 // interpret it as UTF-16 and convert it to UTF-8. 51 // 52 // The output of this function takes the *appearance* of JSON but is not in 53 // fact valid according to RFC 4627. 54 std::string EscapeBytesAsInvalidJSONString(std::string_view str, 55 bool put_in_quotes); 56 57 } // namespace base 58 59 #endif // BASE_JSON_STRING_ESCAPE_H_ 60