如何在Python中引用外部CSV替换JSON文件中的变量?
解决方案:XML转JSON并替换CSV中定义的变量含义
实现步骤
- 读取
SyslogEventID.csv,构建变量(如A00、A01)到对应含义的映射字典 - 递归遍历JSON对象的所有字符串字段,替换其中匹配的变量
- 将处理后的JSON写入文件
完整代码
import xmltodict import json import csv import re # 从CSV读取变量-含义映射 def load_event_mappings(csv_path): mapping = {} # 假设CSV第一列是变量(如A00),第二列是对应含义,若列名不同请调整读取逻辑 with open(csv_path, 'r', encoding='utf-8') as f: reader = csv.reader(f) next(reader) # 跳过表头(无表头则删除此行) for row in reader: if len(row) >= 2: event_id = row[0].strip() description = row[1].strip() mapping[event_id] = description return mapping # 递归替换JSON对象中的变量 def replace_variables(data, mapping): if isinstance(data, dict): return {k: replace_variables(v, mapping) for k, v in data.items()} elif isinstance(data, list): return [replace_variables(item, mapping) for item in data] elif isinstance(data, str): # 用正则匹配独立变量,避免部分匹配(比如A000不会被误拆为A00+0) pattern = re.compile(r'\b(' + '|'.join(re.escape(k) for k in mapping.keys()) + r')\b') return pattern.sub(lambda m: mapping[m.group()], data) else: return data # 整合原有逻辑与变量替换 if __name__ == "__main__": # 读取XML转为JSON对象 with open('DS7.xml', 'r', encoding='utf-8') as myfile: obj = xmltodict.parse(myfile.read()) # 加载变量映射 event_mapping = load_event_mappings('SyslogEventID.csv') # 执行变量替换 processed_obj = replace_variables(obj, event_mapping) # 写入处理后的JSON文件 with open('finaldata.txt', 'w', encoding='utf-8') as f: json.dump(processed_obj, f, ensure_ascii=False, indent=4)
关键说明
- CSV读取适配:如果CSV有自定义表头(如列名为
EventID和Meaning),可改用csv.DictReader简化逻辑:with open(csv_path, 'r', encoding='utf-8') as f: reader = csv.DictReader(f) for row in reader: event_id = row['EventID'].strip() description = row['Meaning'].strip() mapping[event_id] = description - 替换精度保障:使用
\b(单词边界)正则规则,确保只替换独立的目标变量,避免误替换包含变量的长字符串 - 编码问题处理:所有文件操作指定
encoding='utf-8',避免中文乱码
内容的提问来源于stack exchange,提问作者Vishwanath B
相关产品推荐
相关产品推荐

