How to beautify JSON Data programmatically?

JSON is a popular data format used for representing structured data. Despite its popularity, working with JSON data can be challenging. One of the biggest challenges is dealing with data that is not formatted correctly or contains errors.

How to beautify JSON Data in the most popular programming languages

How to beautify JSON Data in JavaScript?

Prettifying JSON data in JavaScript is surprisingly simple. It is a one-liner that makes all the difference.

To convert JSON object value to a JSON string we typically use JSON.Stringify(obj) method like this:

var obj = {"policy": {
                "NTLM": false,
                "domain": "https://domain.com"
            },"isUnique": true,"selectedFilterLists": "none"};
console.log(JSON.stringify(obj, undefined, 4));
Pretty-Print JSON in JavaScript

This will result in the following output:

 '{
    "policy": {
        "NTLM": false,
        "domain": "https://domain.com"
    },
    "isUnique": true,
    "selectedFilterLists": "none"
}'

JSON.stringify method takes 3 parameters:

  1. value: Value to convert into a JSON string
  2. replacer: It is an optional parameter. An altering function or an array of strings or numbers naming properties  value that should be included in the output.
  3. space: A String or Number an object that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes.

Native REST API Client for macOS

Build, test, and describe APIs. Fast.

Download Now

How to beautify JSON Data in Python?

Python has a built-in module called JSON that can work with JSON data.

To beautify JSON data, we can use the json.dumps() function. This function takes an indent argument that specifies the number of spaces to indent for each nesting level. We can also use the sort_keys argument to sort the keys in alphabetical order.

Example:

import json
data = {'name': 'John', 'age': 27, 'city': 'New York'}
print(json.dumps(data, indent=4, sort_keys=True))
Pretty-Print JSON in Python

Output:

{
    "age": 27,
    "city": "New York",
    "name": "John"
}

How to beautify JSON Data in Java?

There are many Java libraries that can beautify JSON strings.

To pretty-print JSON data in Java using GSON:

  1. Create GSON object
  2. Parse input JSON string into a JsonElement
  3. Prettify data using toJson method.
import com.google.gson.*;

final String jsonString = "{\"one\":\"AAA\",\"two\":[\"BBB\",\"CCC\"],\"three\":{\"four\":\"DDD\",\"five\":[\"EEE\",\"FFF\"]}}";

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement data = JsonParser.parseString(jsonString);
String prettyJsonString = gson.toJson(data);
Pretty-Print JSON in Java

Output:

{
  "one" : "AAA",
  "two" : [ "BBB", "CCC" ],
  "three" : {
    "four" : "DDD",
    "five" : [ "EEE", "FFF" ]
  }
}

How to beautify JSON Data in Swift?

Swift also has a built-in method to pretty-print JSON strings from data. As described in my previous article, we just need to feed the JSON data to the JSONSerialization to create a parsed JSON object using prettyPrinted option:

import Foundation

extension Data {
    var prettyPrintedJSONString: NSString? { /// NSString gives us a nice sanitized debugDescription
        guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
              let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
              let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }

        return prettyPrintedString
    }
}

let str = "{\"foo\": \"bar\"}".data(using: .utf8)!.prettyPrintedJSONString!
debugPrint(str)

/* prints:
 {
    "foo" : "bar"
 }
*/
Pretty-Print JSON in Swift