jsonformatpretty-printballerina

How to print formatted JSON value in Ballerina


Please run the following example code.

import ballerina/io;

public function main() {
    json j = {"id": 1, "name": "John", "address": {"city": "New York", "country": "USA"}};
    io:println(j);
}

Here j is printed in the console without formatting as shown below.

{"id":1,"name":"John","address":{"city":"New York","country":"USA"}}

What is the recommended way to print formatted JSON value?


Solution

  • You can use the thisarug/prettify package to pretty print a JSON value.

    import ballerina/io;
    import thisarug/prettify;
    
    public function main() {
        json j = {"id": 1, "name": "John", "address": {"city": "New York", "country": "USA"}};
        io:println(prettify:prettify(j));
    }
    

    This code will print the following:

    {
        "id": 1,
        "name": "John",
        "address": {
            "city": "New York",
            "country": "USA"
        }
    }