如何使用Python提取file1.json的username并替换到file2.json对应位置
实现逻辑
你已经完成了file1.json用户名的提取,后续只需要读取file2.json、修改目标字段、回写文件即可,步骤如下:
- 读取file2.json内容,反序列化为Python字典
- 按照file2的结构定位到
"env.user_data"字段,将提取到的用户名列表赋值给该字段 - 将修改后的字典序列化为JSON格式,写入回file2.json文件
完整代码示例
import json def name(): contents= [] try: with open("file1.json", 'r') as f: contents = json.load(f) except Exception as e: print(e) data = [item.get('username') for item in contents] return data if __name__ == "__main__": # 提取用户名列表 test = name() print(test) # 处理file2.json替换逻辑 try: # 读取file2.json内容 with open("file2.json", "r", encoding="utf-8") as f: file2_data = json.load(f) # 按结构定位目标字段赋值 file2_data["profile"][0]["custom_data"]["env.user_data"] = test # 写回修改后的内容到file2.json with open("file2.json", "w", encoding="utf-8") as f: # indent=2用于格式化输出JSON,ensure_ascii=False避免特殊字符乱码 json.dump(file2_data, f, indent=2, ensure_ascii=False) print("字段替换完成") except Exception as e: print(f"处理file2.json出错:{e}")
补充说明
如果实际场景中profile数组存在多个元素需要批量替换,把赋值逻辑改为遍历file2_data["profile"]列表逐个修改即可。
内容的提问来源于stack exchange,提问作者ansh1
相关产品推荐
相关产品推荐

