保存json时,保存成自己喜欢的格式的方法(而不是直接保存成格式化的json文档)

前言,博主是如何把格式话的json格式保存成自己喜欢的json格式的

保存成格式化的json文档的格式:

带缩进格式

with open(output_file, 'w') as f:
    json.dump(output_data, f, indent=4)

全部保存成一行

JSON 文件在打开时不是格式化的(没有缩进和换行),全都保存在一行

with open(output_file, 'w') as f:
    json.dump(output_data, f, separators=(',', ':'))

每条数据保存成一行:

# 保存到变量
saved_results = output_data

# 保存到文件
output_file = 'output.json'

with open(output_file, 'w') as f:
    for item in output_data:
        json_str = json.dumps(item, separators=(',', ':'))
        f.write(json_str + '\n')

print(f"Results have been saved to {output_file}")

保存成自己喜欢的格式

总结:json保存的格式并不是一成不变的,我们可以使用json中自带的字符串替换工具,来自己为其添加一些回车换行符,以及别的缩进符啥的:

比如将以下数据

{"project":"OpenAI","team":[{"name":"Alice","tasks":[{"task":"Research","status":"completed"},{"task":"Writing","status":"pending"}]},{"name":"Bob","tasks":[{"task":"Development","status":"in progress"},{"task":"Testing","status":"not started"}]}]}

通过replace替换后保存

比如我们通过使用replace函数,在想添加回车'\n'的地方,在替换的文字中添加上'\n',就可以:

import json

# 示例数据
example_data_3 = {"project": "OpenAI", "team": [{"name": "Alice", "tasks": [{"task": "Research", "status": "completed"}, {"task": "Writing", "status": "pending"}]}, {"name": "Bob", "tasks": [{"task": "Development", "status": "in progress"}, {"task": "Testing", "status": "not started"}]}]}

# 保存到文件的函数
def save_pretty_json(data, output_file):
    with open(output_file, 'w') as f:
        json_str = json.dumps(data, separators=(',', ':'))
        json_str_with_newlines = json_str.replace('":[{"', '":[\n{"')
        json_str_with_newlines = json_str_with_newlines.replace('d"},{"t', 'd"},\n{"t')
        json_str_with_newlines = json_str_with_newlines.replace('I","tet', 'I",\n"te')
        json_str_with_newlines = json_str_with_newlines.replace('g"}]},{"n', 'g"}]},\n{"n')
        json_str_with_newlines = json_str_with_newlines.replace('s"},{"t', 's"},\n{"t')
        f.write(json_str_with_newlines)
    print(f"Results have been saved to {output_file}")

# 保存示例数据到文件
def save_json(data, output_file):
    with open(output_file, 'w') as f:
        json.dump(data, f, separators=(',', ':'))

save_json(example_data_3,'output5.json')
save_pretty_json(example_data_3, 'output6.json')

我们还可以进一步的,自己控制添加回车缩进,处理成自己方便审阅数据的样子。

使用上面的替换字符串代码后,我就把原始的数据处理成了下面这样
在这里插入图片描述

碎碎念

一定还有其他好用的手动处理数据成自己喜欢样式的方法。如果还有其他方法的话,大家留言哈,感谢

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值