JSON data can sometimes be hard to read when it's all on one line. Making it look nice with proper spacing and line breaks, also known as pretty printing, makes working with JSON much simpler.
Why Pretty Print JSON?
Reading unformatted JSON can be a headache, especially for complex data. Pretty printing helps you quickly understand the structure and find the information you need.
How to Make JSON Readable
Dart provides a simple way to format JSON strings using the dart:convert
library. You just need to use the JsonEncoder.withIndent
constructor.
The Code You Need
Here's the code snippet that does the magic:
import 'dart:convert';
// Your unformatted JSON data (replace with your actual data)
var data = {
'name': 'John Doe',
'age': 30,
'isStudent': false,
'courses': ['Math', 'Science']
};
// Create an encoder with an indent (using two spaces here)
var encoder = const JsonEncoder.withIndent(' ');
// Convert your data to a pretty-printed JSON string
String prettyprint = encoder.convert(data);
// Now 'prettyprint' holds the nicely formatted JSON string
print(prettyprint);
Breaking Down the Steps
import 'dart:convert';
: This line brings in the necessary tools for working with JSON.var encoder = const JsonEncoder.withIndent(' ');
: We create aJsonEncoder
that knows how to add indents. We tell it to use two spaces for each level of indentation. You can use tabs (\t
) or other strings too.String prettyprint = encoder.convert(data);
: This line takes your JSON data (data
, which can be a Map or List) and turns it into a nicely formatted JSON string using the encoder we set up.
That's it! Now you have a clean, easy-to-read JSON string.