formatJson method

String formatJson([
  1. JsonFormattingOptions options = standardJsonFormatting
])

Get JSON String formatted.

{@category encoder}

Implementation

String formatJson([
  JsonFormattingOptions options = standardJsonFormatting,
]) {
  final indenting = options.indentation;

  final colonPadding = options.colonPadding;

  final characters = split("").normalizeSpaces;

  final output = <String>[];

  var depth = 0;

  for (final character in characters) {
    final buffer = StringBuffer();
    if (character == "{") {
      depth += 1;
      buffer.write("{\n");
      for (var i = 0; i < depth; i++) {
        for (var y = 0; y < indenting; y++) {
          buffer.write(" ");
        }
      }
      output.add(buffer.toString());
    } else if (character == "}") {
      buffer.write("\n");
      depth -= 1;
      for (var i = 0; i < depth; i++) {
        for (var y = 0; y < indenting; y++) {
          buffer.write(" ");
        }
      }
      buffer.write("}");
      output.add(buffer.toString());
    } else if (character == "[") {
      depth += 1;
      buffer.write("[\n");
      for (var i = 0; i < depth; i++) {
        for (var y = 0; y < indenting; y++) {
          buffer.write(" ");
        }
      }
      output.add(buffer.toString());
    } else if (character == "]") {
      buffer.write("\n");
      depth -= 1;
      for (var i = 0; i < depth; i++) {
        for (var y = 0; y < indenting; y++) {
          buffer.write(" ");
        }
      }
      buffer.write("]");
      output.add(buffer.toString());
    } else if (character == ":") {
      for (var i = 0; i < colonPadding; i++) {
        output.add(" ");
      }

      output.add(":");
      for (var i = 0; i < colonPadding; i++) {
        output.add(" ");
      }
    } else if (character == ",") {
      buffer.write(",\n");
      for (var i = 0; i < depth; i++) {
        for (var y = 0; y < indenting; y++) {
          buffer.write(" ");
        }
      }
      output.add(buffer.toString());
    } else {
      output.add(character);
    }
  }
  return output.join();
}