blob: 6608b3b5e4a8fdf920b7aa13ade17f811a0b9e74 [file] [log] [blame]
Vitaly Bukacbed2062015-08-17 12:54:05 -07001// 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
12#include "base/base_export.h"
13#include "base/strings/string_piece.h"
14
15namespace base {
16
17// Appends to |dest| an escaped version of |str|. Valid UTF-8 code units will
18// pass through from the input to the output. Invalid code units will be
19// replaced with the U+FFFD replacement character. This function returns true
20// if no replacement was necessary and false if there was a lossy replacement.
21// On return, |dest| will contain a valid UTF-8 JSON string.
22//
23// Non-printing control characters will be escaped as \uXXXX sequences for
24// readability.
25//
26// If |put_in_quotes| is true, then a leading and trailing double-quote mark
27// will be appended to |dest| as well.
Vitaly Buka60b8f002015-08-20 13:47:48 -070028bool EscapeJSONString(const StringPiece& str,
29 bool put_in_quotes,
30 std::string* dest);
Vitaly Bukacbed2062015-08-17 12:54:05 -070031
Vitaly Bukacbed2062015-08-17 12:54:05 -070032// Helper functions that wrap the above two functions but return the value
33// instead of appending. |put_in_quotes| is always true.
Vitaly Buka60b8f002015-08-20 13:47:48 -070034std::string GetQuotedJSONString(const StringPiece& str);
Vitaly Bukacbed2062015-08-17 12:54:05 -070035
36// Given an arbitrary byte string |str|, this will escape all non-ASCII bytes
37// as \uXXXX escape sequences. This function is *NOT* meant to be used with
38// Unicode strings and does not validate |str| as one.
39//
40// CAVEAT CALLER: The output of this function may not be valid JSON, since
41// JSON requires escape sequences to be valid UTF-16 code units. This output
42// will be mangled if passed to to the base::JSONReader, since the reader will
43// interpret it as UTF-16 and convert it to UTF-8.
44//
45// The output of this function takes the *appearance* of JSON but is not in
46// fact valid according to RFC 4627.
Vitaly Buka60b8f002015-08-20 13:47:48 -070047std::string EscapeBytesAsInvalidJSONString(const StringPiece& str,
48 bool put_in_quotes);
Vitaly Bukacbed2062015-08-17 12:54:05 -070049
50} // namespace base
51
52#endif // BASE_JSON_STRING_ESCAPE_H_