Home > Mobile >  How to do indentation in json file?
How to do indentation in json file?

Time:09-23

I trying to write to the jsong file. I want my json file should be written with indentation. But It has only one line. It is possible in python. How to do it in ballerina.

[
{
    "employeeId": 2413,
    "odometerReading": 4089,
    "gallons": 21.682,
    "gasPrice": 3.46
},
{
    "employeeId": 3423,
    "odometerReading": 6582,
    "gallons": 15.248,
    "gasPrice": 4.56
},
{
    "employeeId": 2413,
    "odometerReading": 4127,
    "gallons": 4.221,
    "gasPrice": 3.40
},
{
    "employeeId": 2413,
    "odometerReading": 4349,
    "gallons": 11.192,
    "gasPrice": 4.10
},
{
    "employeeId": 3423,
    "odometerReading": 6767,
    "gallons": 8.696,
    "gasPrice": 3.34
},
{
    "employeeId": 2413,
    "odometerReading": 4547,
    "gallons": 9.197,
    "gasPrice": 2.90
}

]

But My file has

[{"employeeId":2413, "gasFillUpCount":4, "totalFuelCost":161.92962, "totalGallons":46.292, "totalMilesAccured":458}, {"employeeId":3423, "gasFillUpCount":2, "totalFuelCost":98.57552, "totalGallons":23.944, "totalMilesAccured":185}]

CodePudding user response:

Adding to the @ThisaruG answer, if you want the indentation(without the escape characters) in the JSON file, you can use the io:fileWriteString instead of io:fileWriteJson. Please refer to the following example,

import ballerina/io;
import thisarug/prettify;

public function main() returns error? {
    // Initializes the JSON file path and content.
    string jsonFilePath = "./files/jsonFile.json";

    json jsonContent = [{"employeeId": 2413, "odometerReading": 4089, "gallons": 21.682, "gasPrice": 3.46}];

    string prettified = prettify:prettify(jsonContent);

    check io:fileWriteString(jsonFilePath, prettified);
}

CodePudding user response:

You can use the prettify library in Ballerina for this. It is a third party library though.

import thisarug/prettify;

public function main() {
    json value = { name: “Sam” };
    string prettified = prettify:prettify(value);

}

You can check out the documentation here: https://central.ballerina.io/thisarug/prettify

  • Related