Skip to content

Instantly share code, notes, and snippets.

@kasperpeulen
Last active October 9, 2024 21:44
Show Gist options
  • Save kasperpeulen/d61029fc0bc6cd104602 to your computer and use it in GitHub Desktop.
Save kasperpeulen/d61029fc0bc6cd104602 to your computer and use it in GitHub Desktop.
How to pretty-print JSON using Dart.
import 'dart:convert';
main() {
Map json = {
'name' : 'Kasper Peulen',
'best_language': 'dart',
'best_chat': 'https://dartlang.slack.com'
};
JsonEncoder encoder = new JsonEncoder.withIndent(' ');
String prettyprint = encoder.convert(json);
print(prettyprint);
}
name: dart.convert_JsonEncoder.withIndent
description: |
How to pretty-print JSON using Dart.
How to display JSON in an easy-to-read (for human readers) format.
tags: 'json pretty-print'
homepage: https://gist.github.com/kasperpeulen/d61029fc0bc6cd104602
environment:
sdk: '>=1.0.0 <2.0.0'
@RohanArora13
Copy link

For long logs, this works fine:

  static JsonDecoder decoder = JsonDecoder();
  static JsonEncoder encoder = JsonEncoder.withIndent('  ');

  static void prettyPrintJson(String input) {
    var object = decoder.convert(input);
    var prettyString = encoder.convert(object);
    prettyString.split('\n').forEach((element) => print(element));
  }

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment