Pretty Print Json in Dart

Pretty Print Json in Dart

code
Colin Stodd
Dart,JSON,Pretty Print,Flutter,OpenWeatherMap
30 Jan 2020 (Published)

For the past 4-6 months I’ve been learning Flutter, which is framework for building mobile (but now also web) apps on both iOS and Android devices using the same codebase. I’ll let you do the research on Flutter but if you landed on this page, there’s probably a good chance you already know about Flutter. Nevertheless, below is a function to help you “pretty-print” JSON data into your Dart terminal.

FYI: Dart is the programming language that Flutter uses, which are both created and maintained by Google.

This function can be used just like you would with a print('some message') in Dart, but the parameter has to be a String of JSON.

import 'dart:convert'; //Don't forget to import this

void prettyPrintJson(String input) {
  const JsonDecoder decoder = JsonDecoder();
  const JsonEncoder encoder = JsonEncoder.withIndent('  ');
  final dynamic object = decoder.convert(input);
  final dynamic prettyString = encoder.convert(object);
  prettyString.split('\n').forEach((dynamic element) => print(element));
}

You would use/call it like so

prettyPrintJson(validJSON.toString());

Or in a realistic example using OpenWeatherMap’s API:

import 'dart:convert';
import 'package:appName/utilities/constants.dart';
import 'package:appName/utilities/pretty_print.dart';
import 'package:http/http.dart' as http;

class NetworkHelper {
  Future<dynamic> getWeatherData({double lon, double lat}) async {
    final String url = 'https://api.openweathermap.org/data/2.5/weather?lat=$lat&lon=$lon&appid=$kApiKey';

    final http.Response response = await http.get(url);
    /*
    Below we are calling the prettyPrintJson() with the response.body
    But you need to make sure it's in String format.
    */
    prettyPrintJson(response.body.toString());
    if (response.statusCode == 200) {
      return jsonDecode(response.body);
    } else {
      print('Error: response.statusCode not 200. Was: ${response.statusCode}');
      return response.statusCode;
    }
  }
}

Below is an image of the output. As you can see it’s much more legible to the human eye.