JSON合并工具
将多个JSON对象深度合并为一个。
JSON 对象 #1
JSON 对象 #2
关于此工具
JSON 合并工具使用深层合并将多个 JSON 对象组合成一个统一的结构,这意味着嵌套对象和数组是智能地组合而不是简单地覆盖。对于处理配置文件、API 响应或数据聚合工作流的开发人员来说,当需要来自不同来源的数据合并同时保留每个输入的有意义信息时,这是必不可少的。
要使用该工具,请将 JSON 对象粘贴到输入字段中,选择您首选的合并策略(例如覆盖、数组连接或深层合并),然后单击合并按钮。该工具会自动处理嵌套结构,根据您选择的策略解决冲突。常见用例包括合并环境配置、组合 API 有效负载、整合来自多个服务的设置以及集成测试夹具或模拟数据。
该工具完全在浏览器中运行,因此您的 JSON 数据永远不会离开您的计算机,这使其对敏感配置也很安全。请记住,合并行为取决于您选择的策略—了解您是否要合并嵌套对象、附加数组或替换值,以实现所需的精确结果。
常见问题
代码实现
import json
from copy import deepcopy
def deep_merge(base: dict, override: dict, strategy: str = "last_wins") -> dict:
"""
Deep merge two dicts.
strategy: 'last_wins' | 'first_wins' | 'array_concat'
"""
result = deepcopy(base)
for key, value in override.items():
if key in result:
if isinstance(result[key], dict) and isinstance(value, dict):
result[key] = deep_merge(result[key], value, strategy)
elif isinstance(result[key], list) and isinstance(value, list) and strategy == "array_concat":
result[key] = result[key] + value
else:
if strategy != "first_wins":
result[key] = deepcopy(value)
else:
result[key] = deepcopy(value)
return result
# Example
a = {"name": "Alice", "scores": [1, 2], "meta": {"v": 1}}
b = {"name": "Bob", "scores": [3, 4], "meta": {"v": 2, "new": True}}
print(json.dumps(deep_merge(a, b, "last_wins"), indent=2))
print(json.dumps(deep_merge(a, b, "first_wins"), indent=2))
print(json.dumps(deep_merge(a, b, "array_concat"),indent=2))
Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.