You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ballerina中为JSON文件添加缩进格式?

在Ballerina中生成带缩进的格式化JSON文件

问题

我尝试写入JSON文件,希望生成的JSON文件带有缩进格式,但目前生成的内容仅为单行。已知Python可实现该功能,请问如何在Ballerina中完成此操作?

期望的格式化JSON示例:

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

实际生成的JSON内容:

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

解决方案

在Ballerina中,你可以通过json模块的序列化工具生成带缩进的格式化JSON,再写入文件,有两种常用方式:

方式一:使用json:serialize()配置缩进参数

通过指定json:SerializeConfig的indent字段,自定义缩进空格数,示例代码如下:

import ballerina/io;
import ballerina/json;

public function main() returns error? {
    // 示例数据,替换为你的实际数据
    json employeeData = [
        {"employeeId": 2413, "gasFillUpCount": 4, "totalFuelCost": 161.92962, "totalGallons": 46.292, "totalMilesAccured": 458},
        {"employeeId": 3423, "gasFillUpCount": 2, "totalFuelCost": 98.57552, "totalGallons": 23.944, "totalMilesAccured": 185}
    ];

    // 配置序列化规则,设置缩进为4个空格
    json:SerializeConfig serializeConfig = {indent: 4};
    string formattedJson = check json:serialize(employeeData, serializeConfig);

    // 将格式化后的JSON写入文件
    check io:writeFile("formatted_output.json", formattedJson);
}

方式二:使用json:prettyPrint()快速格式化

如果不需要自定义缩进数,json:prettyPrint()会默认生成带4空格缩进的格式化JSON,代码更简洁:

import ballerina/io;
import ballerina/json;

public function main() returns error? {
    json employeeData = [
        {"employeeId": 2413, "gasFillUpCount": 4, "totalFuelCost": 161.92962, "totalGallons": 46.292, "totalMilesAccured": 458},
        {"employeeId": 3423, "gasFillUpCount": 2, "totalFuelCost": 98.57552, "totalGallons": 23.944, "totalMilesAccured": 185}
    ];

    string formattedJson = json:prettyPrint(employeeData);
    check io:writeFile("pretty_output.json", formattedJson);
}

核心说明

  • 两种方式都会将紧凑的单行JSON转换为带换行和缩进的结构化格式,满足你的需求。
  • check关键字用于处理序列化或文件写入过程中可能出现的错误,符合Ballerina的错误处理规范。

内容的提问来源于stack exchange,提问作者Vishal Vikal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 14:40:50