简体   繁体   中英

How to do indentation in json file?

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

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);
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM