簡體   English   中英

如何在 json 文件中進行縮進?

[英]How to do indentation in json file?

我試圖寫入 jsong 文件。 我希望我的 json 文件應該帶有縮進。 但它只有一行。 在 python 中是可能的。 如何在芭蕾舞演員中做到這一點。

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

]

但我的文件有

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

添加到@ThisaruG 答案中,如果您想要 JSON 文件中的縮進(不帶轉義字符),您可以使用io:fileWriteString而不是io:fileWriteJson 請參考以下示例,

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

為此,您可以使用 Ballerina 中的prettify庫。 雖然它是第三方庫。

import thisarug/prettify;

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

}

您可以在此處查看文檔: https://central.ballerina.io/thisarug/prettify

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM