Python 处理 JSON 格式数据
Author: ACatSmiling
Since: 2024-10-09
需求:将文件中的 JSON 格式数据,指定 Key 的值替换。
对于文件的整个文本为 JSON 格式的数据。示例:
{ 'A': { 'a': 23.45, 'b': 56.78, 'c': 89.01 } }
Python 代码:
import json # 读取原始 JSON 数据 with open('original_data.json', 'r') as file: data = json.load(file) # 处理数据 inner_data = data['A'] inner_data['a'] /= 100 inner_data['b'] /= 100 inner_data['c'] /= 100 # 将处理后的数据重新封装为 JSON 并写入文件 with open('processed_data.json', 'w') as file: json.dump(data, file)
对于文件的每一行为 JSON 格式的数据。示例:
{'A': {'a': 23.45, 'b': 56.78, 'c': 89.01}} {'A': {'a': 23.45, 'b': 56.78, 'c': 89.01}} {'A': {'a': 23.45, 'b': 56.78, 'c': 89.01}}
Python 代码:
import json with open('original_file.txt', 'r') as infile, open('processed_file.txt', 'w') as outfile: for line in infile: data = json.loads(line) for key, inner_dict in data.items(): if 'a' in inner_dict: inner_dict['a'] /= 100 if 'b' in inner_dict: inner_dict['b'] /= 100 if 'c' in inner_dict: inner_dict['c'] /= 100 outfile.write(json.dumps(data) + '\n')
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了