Python代码技巧: 在JSON字符串每个','后添加换行符

在处理JSON数据时,为了提高代码的可读性,我们通常希望对JSON字符串进行格式化,例如在每个','后面添加一个换行符。

以下是一些常用的方法:

1. 使用json.dumps()函数的indent和separators参数

import json

data = {
'description': 'The dataset of the competition', 
'labels': {
'0': 'background', 
'1': 'liver', 
'2': 'spleen', 
'3': 'left kidney', 
'4': 'right kidney'
}, 
'modality': {'0': 'CT'}, 
'name': 'dataset', 
'numTraining': 100, 
'numValidation': 20, 
'numTest': 20, 
'training': [], 
'validation': [], 
'test': []
}

# 使用indent参数控制缩进级别,separators参数指定分隔符
json_data = json.dumps(data, indent=4, separators=(',', ': '))

# 打印格式化的JSON字符串
print(json_data)

# 将格式化的JSON字符串写入文件
with open('data.json', 'w') as json_file:
    json.dump(data, json_file, indent=4, separators=(',', ': '))

2. 使用字符串的replace()方法

# ... (代码的前一部分与方法1相同)

# 将数据集转换为JSON字符串
json_data = json.dumps(data)

# 将每个','替换为',
'
formatted_json_data = json_data.replace(',', ',
')

# 打印格式化的JSON字符串
print(formatted_json_data)

# 将格式化的JSON字符串写入文件
with open('data.json', 'w') as json_file:
    json_file.write(formatted_json_data)

总结

以上两种方法都可以实现在JSON字符串每个','后添加换行符的效果,选择哪种方法取决于个人偏好和实际需求。

Python代码技巧: 在JSON字符串每个','后添加换行符

原文地址: https://www.cveoy.top/t/topic/fBa7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录