在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
相关产品推荐
相关产品推荐

