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

在Ballerina中打印格式化JSON值的推荐方法是什么?

如何在Ballerina中打印格式化的JSON值?

你提供的示例代码运行后会输出无压缩的JSON字符串:

import ballerina/io;

public function main() {
    json j = {"id": 1, "name": "John", "address": {"city": "New York", "country": "USA"}};
    io:println(j);
}

输出结果:

{"id":1,"name":"John","address":{"city":"New York","country":"USA"}}

要打印格式化后的JSON,推荐使用以下两种方法:

方法1:使用io:printJson函数

Ballerina的io模块提供了专门的printJson函数,支持通过indent参数指定缩进空格数,直接输出格式化后的JSON:

import ballerina/io;

public function main() {
    json j = {"id": 1, "name": "John", "address": {"city": "New York", "country": "USA"}};
    // 指定缩进为4个空格
    io:printJson(j, indent = 4);
}

运行后输出:

{
    "id": 1,
    "name": "John",
    "address": {
        "city": "New York",
        "country": "USA"
    }
}

方法2:使用json:toString方法格式化后打印

如果需要先将JSON转为格式化的字符串再处理,可以用json模块的toString方法,传入indent参数:

import ballerina/io;
import ballerina/json;

public function main() {
    json j = {"id": 1, "name": "John", "address": {"city": "New York", "country": "USA"}};
    string formattedJson = check json:toString(j, indent = 4);
    io:println(formattedJson);
}

该方法会先生成格式化的JSON字符串,再通过io:println输出,结果和方法1一致。


内容的提问来源于stack exchange,提问作者Kavindu Gimhan Zoysa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 18:39:57