JSON Merge (Python)
jsonmerge is a Python library designed for merging a series of JSON documents into a single document. It is particularly useful for consolidating contributions from different authors to a common document or managing consecutive versions where fields are updated over time. The library leverages JSON Schema to define and apply various merge strategies for different parts of the document. The current version is 1.9.2, with an infrequent release cadence (e.g., updates in 2017 and 2023).
Warnings
- gotcha The library primarily uses JSON Schema Draft 4 by default for defining merge strategies. Newer JSON Schema drafts might introduce different behaviors or keywords. If you are using schemas based on a different draft, you might need to specify a compatible `jsonschema.Validator` subclass via the `validatorclass` argument in the `Merger` constructor.
- gotcha When using schema-driven merging, `jsonmerge` does not inherently validate input documents against the schema. It only uses the schema to determine merge strategies. Malformed input JSON or documents not conforming to the schema can lead to unexpected merge results or errors if not pre-validated.
- breaking Support for Python 2.6 has been removed. While older documentation might mention Python 2.7 support, current versions (1.9.2 and later) explicitly require Python 3.5 or newer.
- gotcha If your merge schema includes `allOf`, `anyOf`, or `oneOf` keywords without an explicitly defined `mergeStrategy` at that level, `jsonmerge` will raise an error (for `allOf`/`anyOf`) or attempt to find a single valid branch (for `oneOf`), raising an error if none or multiple validate.
- deprecated The `meta` argument for the `version` merge strategy (used to supply document metadata for each version of a field) has been deprecated.
Install
-
pip install jsonmerge
Imports
- merge
from jsonmerge import merge
- Merger
from jsonmerge import Merger
Quickstart
import json
from jsonmerge import merge, Merger
# Basic merge without a schema (uses default objectMerge and overwrite strategies)
base = {"name": "John", "details": {"age": 30, "city": "New York"}, "tags": ["active", "premium"]}
head = {"details": {"age": 31, "country": "USA"}, "occupation": "Engineer", "tags": ["vip"]}
result_basic = merge(base, head)
print(f"Basic merge: {json.dumps(result_basic, indent=2)}")
# Merge with a schema to define specific strategies, e.g., 'append' for arrays
schema = {
"properties": {
"tags": {
"mergeStrategy": "append"
}
}
}
merger = Merger(schema)
result_schema = merger.merge(base, head)
print(f"\nSchema-driven merge (append tags): {json.dumps(result_schema, indent=2)}")