🛠️ToolsShed

JSON 병합 도구

여러 JSON 객체를 하나로 깊이 병합합니다.

JSON 객체 #1
JSON 객체 #2

자주 묻는 질문

코드 구현

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.