批量移除JSON键名p:前缀,循环重命名键名技术需求问询
批量移除JSON键名中的"p:"前缀
针对你这种带多层嵌套的JSON结构,递归遍历处理是最稳妥的方案——毕竟你的数据里有数组、嵌套对象(比如p:Customer数组、p:CommunicationPreferences子对象),必须逐层深入才能覆盖所有带前缀的键。
下面用Python实现完整的处理逻辑,代码简洁且能适配任意层级的嵌套:
import json def clean_p_prefix(obj): if isinstance(obj, dict): # 处理字典:遍历所有键,移除开头的"p:"前缀,再递归处理值 cleaned_dict = {} for key, value in obj.items(): # 只针对以"p:"开头的键做处理,其他键保持原样 new_key = key[2:] if key.startswith("p:") else key cleaned_dict[new_key] = clean_p_prefix(value) return cleaned_dict elif isinstance(obj, list): # 处理数组:遍历每个元素,递归处理内部结构 return [clean_p_prefix(item) for item in obj] else: # 字符串、数字等基础类型直接返回 return obj # 你的原始JSON字符串 raw_json = '''{"status":"success","msg":{"$":{"xmlns:p":"342","xmlns:xsi":"test link","xsi:schemaLocation":"324","source":"234234"},"p:Customer":[{"p:OrderId":["asdasd"],"p:FirstName":["Ingrid"],"p:LastName":["Bryne"],"p:EmailAddress":["asd@ad.com"],"p:BirthDate":["1965-09-23"],"p:CellularPhone":["123465798"],"p:City":["asd"],"p:Country":["asdda"],"p:PostalCode":["23332"],"p:StreetAddress":["asd"],"p:PartnerId":["1-84OPG"],"p:CommunicationPreferences":[{"p:Phone":["12"],"p:Email":["123"],"p:Mail":["231"],"p:SMS":["Nei"]}],"p:ServiceAgreement":[{"p:AgreementType":["Bredbånd - Privat"],"p:AgreementStartDate":["123"],"p:AgreementStatus":["ASS"],"p:Comment":["\n\nse. \n\n"],"p:ListOfAssets":[{"p:Asset":[{"p:ProductPartNumber":["234"],"p:Comments":[""]},{"p:ProductPartNumber":["123"],"p:Comments":[""]},{"p:ProductPartNumber":["12313"],"p:Comments":[""]},{"p:ProductPartNumber":["123"],"p:Comments":[""]},{"p:ProductPartNumber":["123"],"p:Comments":[""]},{"p:ProductPartNumber":["123123"],"p:Comments":[""]}]}]}]}]}}''' # 解析并处理JSON数据 parsed_data = json.loads(raw_json) cleaned_data = clean_p_prefix(parsed_data) # 输出格式化后的结果 print(json.dumps(cleaned_data, indent=2))
关键细节说明
- 递归遍历:自动识别字典和数组,逐层处理所有嵌套层级,不会遗漏深层的
p:前缀键 - 精准匹配:仅对以
p:开头的键做前缀移除,像xmlns:p这类你可能想保留的键不会被修改 - 类型兼容:字符串、数字、换行符等所有基础数据类型都会原封不动保留
运行代码后,你会得到符合预期的结果——所有p:OrderId、p:FirstName这类键都会被重命名为OrderId、FirstName,嵌套结构完全保持原样。
内容的提问来源于stack exchange,提问作者Pritesh Mahajan
相关产品推荐
相关产品推荐

