replaceInvalidJsonCharacters method

String replaceInvalidJsonCharacters(
  1. String json, {
  2. bool isEncodeNonJsonChars = true,
})

Replaces all characters that can not exist unencoded in a JSON with their JSON-encoded representations. We need this step because we seem to be randomly getting very bad JSON back from some connected buttons (especially from the name param which can have carriage returns and other bad things in there)

Implementation

String replaceInvalidJsonCharacters(
  String json, {
  bool isEncodeNonJsonChars = true,
}) {
  var charCodes = <int>[];

  for (final int codeUnit in json.codeUnits) {
    if (codeUnit >= 32 && codeUnit <= 255) {
      // ASCII 32...255 are guaranteed to be valid in a JSON
      charCodes.add(codeUnit);
    } else if (isEncodeNonJsonChars) {
      // Json-encode the character and add the encoded version.
      // For characters that are valid in a JSON, the encoded version is the same
      // as the original (possibly surrounded by "").
      try {
        String encoded = jsonEncode(String.fromCharCode(codeUnit));
        if (encoded.length > 1) {
          if (encoded.startsWith('"')) {
            encoded = encoded.substring(1, encoded.length);
          }
          if (encoded.endsWith('"')) {
            encoded = encoded.substring(0, encoded.length - 1);
          }
        }
        charCodes.addAll(encoded.codeUnits);
      } catch (error) {
        log.warning('error in encoded json char of $codeUnit');
      }
    }
  }
  // and return the created string properly
  return String.fromCharCodes(charCodes);
}