Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get a formatted/indented JSON String from a JSON object?

Tags:

json

dart

Using dart:convert I can get an unindented string with this code.

var unformattedString = JSON.encode(jsonObject);

How do I take a JSON object and convert it to an indented string?

like image 361
seveibar Avatar asked Aug 10 '14 15:08

seveibar


People also ask

What is a JSON formatted string?

JSON structure As described above, JSON is a string whose format very much resembles JavaScript object literal format. You can include the same basic data types inside JSON as you can in a standard JavaScript object — strings, numbers, arrays, booleans, and other object literals.

What is indented JSON?

The indent parameter specifies the spaces that are used at the beginning of a line. We can use the indent parameter of json. dump() to specify the indentation value. By default, when you write JSON data into a file, Python doesn't use indentations and writes all data on a single line, which is not readable.

How do I display formatted JSON data in HTML?

Use the JSON. stringify function to Display formatted JSON in HTML. If you have unformatted JSON It will output it in a formatted way. Or Use <pre> tag for showing code itself in HTML page and with JSON.


2 Answers

One way to do it is by creating a JSONEncoder.withIndent instance.

String getPrettyJSONString(jsonObject){
   var encoder = new JsonEncoder.withIndent("     ");
   return encoder.convert(jsonObject);
}
like image 112
seveibar Avatar answered Sep 27 '22 18:09

seveibar


Use this. it worked for me

String prettyJson(dynamic json) {
    var spaces = ' ' * 4;
    var encoder = JsonEncoder.withIndent(spaces);
    return encoder.convert(json);
}
like image 43
Aminul Haque Aome Avatar answered Sep 27 '22 18:09

Aminul Haque Aome