def replace_invalid_characters(str)
      encoding = str.encoding
      utf8_string = (encoding == Encoding::UTF_8 || encoding == Encoding::ASCII)
      return str if utf8_string && str.valid_encoding?

      temp_str = str.dup
      temp_str.encode!(TEMP_ENCODING, ENCODING_OPTIONS) if utf8_string
      temp_str.encode!('utf-8', ENCODING_OPTIONS)
    end
def replace_invalid_characters(str)
      encoding = str.encoding
      utf8_string = (encoding == Encoding::UTF_8 || encoding == Encoding::ASCII)
      return str if utf8_string && str.valid_encoding?

      temp_str = str.dup
      temp_str.encode!(TEMP_ENCODING, ENCODING_OPTIONS) if utf8_string
      temp_str.encode!('utf-8', ENCODING_OPTIONS)
    end
Replaces invalid characters in a string with arbitrary encoding.

 @param [String] str The string to replace characters
 @return [String] a UTF-8 encoded string
 @see https://github.com/flori/json/commit/3e158410e81f94dbbc3da6b7b35f4f64983aa4e3