如何将JSON字典值复制到含唯一键的其他JSON文件中?
解决JSON值按顺序覆盖到指定RFID键的问题
问题场景
我有一个结构如下的JSON文件,键为数字字符串,值是文件路径:
{ "1": "Filepath/image.png",
"2": "Filepath/image.png"
... }
另外有3个以唯一RFID标签编号作为键的JSON文件,需要将第一个JSON的值按顺序复制,覆盖这3个文件对应键的值。我已将每个目标文件对应的键分别存入3个列表,但运行脚本后提示键不匹配,脚本代码如下:
import json import os import glob import time # Get a list of all the files in the folder files = glob.glob("json/*") # Sort the list of files by modification time files.sort(key=lambda x: os.path.getmtime(x)) # Get the filepath of the newest file newest_file = files[-1] print(newest_file) # Open the newest file and read its contents with open(newest_file, 'r') as f: data = json.load(f) # List of keys to use for each file keys_1 = ["13603414011682", "1360739520482", "136010319878103", "136073122213110", "136034217194177", "1360352372244", "1360739715155", "136072188183203", "136034163207198", "1360738615152", "1201261612531", "136034225204135", "136034230076"] keys_2 = ["136073152053", "136034158129181", "13603412514289", "1360345793206", "136034148129191", "136010459115168", "136034145143180", "1360739170220", "1360351355527", "13603410960251","1360355159163", "13601049817949", "13603422660116"] keys_3 = ["136075353245", "1360743335192", "13601043613070", "1360738365211", "136073133188248", "136034184248234", "13603571150122", "1360341385624", "136074741236", "136074211164181", "111", "222", "333"] # Create the first file subset_1 = {} for i, key in enumerate(keys_1): subset_1[key] = data.get(key, f'Key not found at index {i}') with open('json/charlie.json', 'w') as f: json.dump(subset_1, f) # Create the second file subset_2 = {} for i, key in enumerate(keys_2): subset_2[key] = data.get(key, f'Key not found at index {i}') with open('json/hagrid.json', 'w') as f: json.dump(subset_2, f) # Create the third file subset_3 = {} for i, key in enumerate(keys_3): subset_3[key] = data.get(key, f'Key not found at index {i}') with open('json/junior.json', 'w') as f: json.dump(subset_3, f)
问题原因
脚本中使用data.get(key)尝试按键名匹配取值,但源JSON的键是"1""2"这类序号字符串,而目标列表里的是RFID编号,两者键名完全不匹配,自然无法找到对应值,导致出现"Key not found"的提示。
解决方案
正确思路是按顺序将源JSON的值对应到目标键列表的键上,而不是按键名匹配。修改后的代码如下:
import json import os import glob # 获取文件夹下所有文件 files = glob.glob("json/*") # 按修改时间排序,取最新的源文件 files.sort(key=lambda x: os.path.getmtime(x)) newest_file = files[-1] print(newest_file) # 读取源文件并提取值的列表(Python3.7+字典保持插入顺序) with open(newest_file, 'r') as f: data = json.load(f) source_values = list(data.values()) # 目标RFID键列表 keys_1 = ["13603414011682", "1360739520482", "136010319878103", "136073122213110", "136034217194177", "1360352372244", "1360739715155", "136072188183203", "136034163207198", "1360738615152", "1201261612531", "136034225204135", "136034230076"] keys_2 = ["136073152053", "136034158129181", "13603412514289", "1360345793206", "136034148129191", "136010459115168", "136034145143180", "1360739170220", "1360351355527", "13603410960251","1360355159163", "13601049817949", "13603422660116"] keys_3 = ["136075353245", "1360743335192", "13601043613070", "1360738365211", "136073133188248", "136034184248234", "13603571150122", "1360341385624", "136074741236", "136074211164181", "111", "222", "333"] # 生成第一个目标文件 subset_1 = {} for idx, key in enumerate(keys_1): # 避免源值数量不足时索引越界 subset_1[key] = source_values[idx] if idx < len(source_values) else f'无对应值(索引:{idx})' with open('json/charlie.json', 'w', encoding='utf-8') as f: json.dump(subset_1, f, indent=2, ensure_ascii=False) # 生成第二个目标文件 subset_2 = {} for idx, key in enumerate(keys_2): subset_2[key] = source_values[idx] if idx < len(source_values) else f'无对应值(索引:{idx})' with open('json/hagrid.json', 'w', encoding='utf-8') as f: json.dump(subset_2, f, indent=2, ensure_ascii=False) # 生成第三个目标文件 subset_3 = {} for idx, key in enumerate(keys_3): subset_3[key] = source_values[idx] if idx < len(source_values) else f'无对应值(索引:{idx})' with open('json/junior.json', 'w', encoding='utf-8') as f: json.dump(subset_3, f, indent=2, ensure_ascii=False)
关键修改点
- 提取值列表:将源JSON的
values()转为列表,确保按顺序获取每个文件路径(Python3.7及以上版本的字典会保留插入顺序) - 按索引匹配:循环目标键列表时,通过索引
idx从值列表中取对应位置的内容,而非按键名匹配 - 边界处理:增加索引越界判断,防止源值数量不足时抛出异常
- 优化输出:添加
indent=2格式化JSON,指定编码避免中文乱码
内容的提问来源于stack exchange,提问作者user3568395
相关产品推荐
相关产品推荐

