Converts a quoted json string literal q into a UTF-8-encoded string.
 The rules are different than for Ruby, so we cannot use eval.
 Unquote will raise an error if q contains control characters.
439700
def unquote(q)
    q = q[1...-1]
    a = q.dup # allocate a big enough string
    # In ruby >= 1.9, a[w] is a codepoint, not a byte.
    if rubydoesenc?
      a.force_encoding('UTF-8')
    end
    r, w = 0, 0
    while r < q.length
      c = q[r]
      if c == ?\\
        r += 1
        if r >= q.length
          raise Error, "string literal ends with a \"\\\": \"#{q}\""
        end

        case q[r]
        when ?",?\\,?/,?'
          a[w] = q[r]
          r += 1
          w += 1
        when ?b,?f,?n,?r,?t
          a[w] = Unesc[q[r]]
          r += 1
          w += 1
        when ?u
          r += 1
          uchar = begin
            hexdec4(q[r,4])
          rescue RuntimeError => e
            raise Error, "invalid escape sequence \\u#{q[r,4]}: #{e}"
          end
          r += 4
          if surrogate? uchar
            if q.length >= r+6
              uchar1 = hexdec4(q[r+2,4])
              uchar = subst(uchar, uchar1)
              if uchar != Ucharerr
                # A valid pair; consume.
                r += 6
              end
            end
          end
          if rubydoesenc?
            a[w] = '' << uchar
            w += 1
          else
            w += ucharenc(a, w, uchar)
          end
        else
          raise Error, "invalid escape char #{q[r]} in \"#{q}\""
        end
      elsif c == ?" || c < Spc
        raise Error, "invalid character in string literal \"#{q}\""
      else
        # Copy anything else byte-for-byte.
        # Valid UTF-8 will remain valid UTF-8.
        # Invalid UTF-8 will remain invalid UTF-8.
        # In ruby >= 1.9, c is a codepoint, not a byte,
        # in which case this is still what we want.
        a[w] = c
        r += 1
        w += 1
      end
    end
    a[0,w]
  end
1114555
function qtext() {
        return wrap('qtext', or(
            function qtextFunc1() {
                return compareToken(function qtextFunc2(tok) {
                    var code = tok.charCodeAt(0);
                    var accept =
                        (33 === code) ||
                        (35 <= code && code <= 91) ||
                        (93 <= code && code <= 126);
                    if (opts.rfc6532) {
                        accept = accept || isUTF8NonAscii(tok);
                    }
                    return accept;
                });
            },
            obsQtext
        )());
    }
426356
function escapeString(string) {
  var result = '';
  var char, nextChar;
  var escapeSeq;

  for (var i = 0; i < string.length; i++) {
    char = string.charCodeAt(i);
    // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates").
    if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) {
      nextChar = string.charCodeAt(i + 1);
      if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) {
        // Combine the surrogate pair and store it escaped.
        result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000);
        // Advance index one extra since we already used that char here.
        i++; continue;
      }
    }
    escapeSeq = ESCAPE_SEQUENCES[char];
    result += !escapeSeq && isPrintable(char)
      ? string[i]
      : escapeSeq || encodeHex(char);
  }

  return result;
}
375118
def escape_control_chars!(string)
      string.gsub!(CONTROL_CHARACTERS) do |character|
        UTF8Encoding::REPLACEMENT_SCHEME[character]
      end
      string
    end
486824
def tojson(val, indent=None):
    '''
    
    '''
    options = {'ensure_ascii': True}
    if indent is not None:
        options['indent'] = indent
    return (
        salt.utils.json.dumps(
            val, **options
        ).replace('<', '\\u003c')
         .replace('>', '\\u003e')
         .replace('&', '\\u0026')
         .replace("'", '\\u0027')
    )
328976
public static Optional<String> convertRegexToLiteral(String s) {
    try {
      Pattern.compile(s);
    } catch (PatternSyntaxException e) {
      /* The string is a malformed regular expression which will throw an error at runtime. We will
       * preserve this behavior by not rewriting it.
       */
      return Optional.empty();
    }

    boolean inQuote = false;
    StringBuilder result = new StringBuilder();
    int length = s.length();
    for (int i = 0; i < length; ++i) {
      char current = s.charAt(i);
      if (!inQuote && UNESCAPED_CONSTRUCT.matches(current)) {
        /* If we see an unescaped regular expression control character then we can't match this as a
         * string-literal so give up
         */
        return Optional.empty();
      } else if (current == '\\') {

        /* There should be a character following the backslash. No need to check for string length
         * since we have already ascertained we have a well formed regex */
        char escaped = s.charAt(++i);

        if (escaped == 'Q') {
          inQuote = true;
        } else if (escaped == 'E') {
          inQuote = false;
        } else {
          /* If not starting or ending a quotation (\Q...\E) backslashes can only be used to write
           * escaped constructs or to quote characters that would otherwise be interpreted as
           * unescaped constructs.
           *
           * If they are escaping a construct we can write as a literal string (i.e. one of \t \n
           * \f \r or \\) then we convert to a literal character.
           *
           * If they are escaping an unescaped construct we convert to the relevant character
           *
           * Everything else we can't represent in a literal string
           */
          Character controlChar = REGEXCHAR_TO_LITERALCHAR.get(escaped);
          if (controlChar != null) {
            result.append(controlChar);
          } else if (escaped == '\\') {
            result.append('\\');
          } else if (UNESCAPED_CONSTRUCT.matches(escaped)) {
            result.append(escaped);
          } else {
            return Optional.empty();
          }
        }
      } else {
        /* Otherwise we have a literal character to match so keep going */
        result.append(current);
      }
    }
    return Optional.of(result.toString());
  }
19019
function makeDoubleQuoted( literal ) {
	if ( ! literal || literal.length < 2 ) {
		return undefined;
	}

	// double-quoted string
	if ( literal.charAt( 0 ) === '"' ) {
		return literal.replace( /(\\)/g, '\\$1' );
	}

	// single-quoted string
	if ( literal.charAt( 0 ) === '\'' ) {
		return '"' + literal.substring( 1, literal.length - 1 ).replace( /\\'/g, '\'' ).replace( /(\\|")/g, '\\$1' ) + '"';
	}

	// ES6 string
	if ( literal.charAt( 0 ) === '`' ) {
		return '"' + literal.substring( 1, literal.length - 1 ).replace( /`/g, '\`' ).replace( /(\\|")/g, '\\$1' ) + '"';
	}

	return "";
}
235061
function () {
                    var str, j = i, e;

                    if (input.charAt(j) === '~') { j++, e = true } // Escaped strings
                    if (input.charAt(j) !== '"' && input.charAt(j) !== "'") return;

                    e && $('~');

                    if (str = $(/^"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'/)) {
                        return new(tree.Quoted)(str[0], str[1] || str[2], e);
                    }
                }
1280043
def _unquote_cookie(s: str) -> str:
    
    # If there aren't any doublequotes,
    # then there can't be any special characters.  See RFC 2109.
    if s is None or len(s) < 2:
        return s
    if s[0] != '"' or s[-1] != '"':
        return s

    # We have to assume that we must decode this string.
    # Down to work.

    # Remove the "s
    s = s[1:-1]

    # Check for special sequences.  Examples:
    #    \012 --> \n
    #    \"   --> "
    #
    i = 0
    n = len(s)
    res = []
    while 0 <= i < n:
        o_match = _OctalPatt.search(s, i)
        q_match = _QuotePatt.search(s, i)
        if not o_match and not q_match:  # Neither matched
            res.append(s[i:])
            break
        # else:
        j = k = -1
        if o_match:
            j = o_match.start(0)
        if q_match:
            k = q_match.start(0)
        if q_match and (not o_match or k < j):  # QuotePatt matched
            res.append(s[i:k])
            res.append(s[k + 1])
            i = k + 2
        else:  # OctalPatt matched
            res.append(s[i:j])
            res.append(chr(int(s[j + 1 : j + 4], 8)))
            i = j + 4
    return _nulljoin(res)
904436
function quoteLiteral(value) {

    var literal = null;
    var explicitCast = null;

    if (value === undefined || value === null) {
        return 'NULL';
    } else if (value === false) {
        return "'f'";
    } else if (value === true) {
        return "'t'";
    } else if (value instanceof Date) {
        return "'" + formatDate(value.toISOString()) + "'";
    } else if (value instanceof Buffer) {
        return "E'\\\\x" + value.toString('hex') + "'";
    } else if (Array.isArray(value) === true) {
        var temp = [];
        for (var i = 0; i < value.length; i++) {
            if (Array.isArray(value[i]) === true) {
                temp.push(arrayToList(i !== 0, value[i], quoteLiteral))
            } else {
                temp.push(quoteLiteral(value[i]));
            }
        }
        return temp.toString();
    } else if (value === Object(value)) {
        explicitCast = 'jsonb';
        literal = JSON.stringify(value);
    } else {
        literal = value.toString().slice(0); // create copy
    }

    var hasBackslash = false;
    var quoted = '\'';

    for (var i = 0; i < literal.length; i++) {
        var c = literal[i];
        if (c === '\'') {
            quoted += c + c;
        } else if (c === '\\') {
            quoted += c + c;
            hasBackslash = true;
        } else {
            quoted += c;
        }
    }

    quoted += '\'';

    if (hasBackslash === true) {
        quoted = 'E' + quoted;
    }

    if (explicitCast) {
        quoted += '::' + explicitCast;
    }

    return quoted;
}
1195067
def json_unicode_to_utf8(data):
    """"""
    if isinstance(data, unicode):
        return data.encode('utf-8')
    elif isinstance(data, dict):
        newdict = {}
        for key in data:
            newdict[json_unicode_to_utf8(
                key)] = json_unicode_to_utf8(data[key])
        return newdict
    elif isinstance(data, list):
        return [json_unicode_to_utf8(elem) for elem in data]
    else:
        return data
1000494
def fix_text_escapes(self, txt: str, quote_char: str) -> str:
        
        def _subf(matchobj):
            return matchobj.group(0).translate(self.re_trans_table)
        if quote_char:
            txt = re.sub(r'\\'+quote_char, quote_char, txt)
        return re.sub(r'\\.', _subf, txt, flags=re.MULTILINE + re.DOTALL + re.UNICODE)
1367833
private char retrieveWrappingQuoteTypeOfJsonMemberNames(String jsonString) {
        char quote = '\"';   //  the default quote character used to specify json member names and string value according to the json specification
        for (char c : jsonString.toCharArray()) {
            if (c == '\'' || c == '\"') {
                quote = c;
                break;
            }
        }
        return quote;
    }
612149
def escape_string_json(st):
    
    ret = []
    c = 0
    ln = len(st)

    escape_chmap = {
        b'\b': b'b',
        b'\f': b'f',
        b'\n': b'n',
        b'\r': b'r',
        b'\t': b't',
        b'\\': b'\\',
        b'\"': b'"',
        b'\/': b'/'
    }

    while c < ln:
        ch = st[c:c+1]
        if ch in escape_chmap:
            ret.append(b'\\' + escape_chmap[ch])
        elif ord(ch) < 0x20:
            ret.append(b'\\u%04X' % ord(ch))
        else:
            ret.append(ch)
        c += 1
    return b''.join(ret)
592652
def unquote_plus(string, encoding='utf-8', errors='replace'):
    
    string = string.replace('+', ' ')
    return unquote(string, encoding, errors)
394868
def utf8(value):
    
    if isinstance(value, _UTF8_TYPES):
        return value
    elif isinstance(value, unicode_type):
        return value.encode("utf-8")
    else:
        return str(value)
142628
def _encode_utf8(self, **kwargs):
        
        if is_py3:
            # This is only valid for Python 2. In Python 3, unicode is
            # everywhere (yay).
            return kwargs

        unencoded_pairs = kwargs
        for i in unencoded_pairs.keys():
            #noinspection PyUnresolvedReferences
            if isinstance(unencoded_pairs[i], types.UnicodeType):
                unencoded_pairs[i] = unencoded_pairs[i].encode('utf-8')
        return unencoded_pairs