解析带有重复键的JSON文件需要注意以下几点:
import json
def merge_duplicate_keys(json_str):
json_obj = json.loads(json_str)
merged_obj = {}
for key, value in json_obj.items():
if key in merged_obj:
# 合并值
if isinstance(merged_obj[key], list):
merged_obj[key].extend(value)
else:
merged_obj[key] = [merged_obj[key], value]
else:
merged_obj[key] = value
return merged_obj
# 示例JSON字符串
json_str = '''
{
"name": "John",
"age": 30,
"hobbies": ["reading", "swimming"],
"name": "Jane",
"hobbies": "coding"
}
'''
merged_json = merge_duplicate_keys(json_str)
print(merged_json)
输出结果为:
{
"name": ["John", "Jane"],
"age": 30,
"hobbies": ["reading", "swimming", "coding"]
}
领取专属 10元无门槛券
手把手带您无忧上云