How to print formatted JSON value in Ballerina

38 views Asked by At

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?

1

There are 1 answers

0
ThisaruG On BEST ANSWER

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"
    }
}