OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Merge JSON configuration objects with explicit replacement rules

Python

Apply a recursive JSON object overlay while replacing whole arrays and preserving null as a value.

Python code excerpt: Merge JSON configuration objects with explicit replacement rules. Version 1.0.0. Read the full recipe for code, sources and recorded test scope.

Use this small CLI to combine a base configuration with an explicit override object. Corresponding objects merge recursively; every other overlay value replaces the base value. Arrays are replaced as a whole. The command reads its request from stdin and returns the result without changing source files.

Before you start

  • Python 3.12 standard library and the reviewed pinned runtime; no third-party packages.
  • One UTF-8 JSON request on stdin, at most 20000 encoded bytes. One extra byte may be read to detect overflow.
  • Use synthetic examples when sharing requests. The program does not read configuration files, environment variables or network services.

Build and check

  1. Save the downloaded source as merge-json-configuration-python.py.
  2. Save the example JSON request below as request.json.
  3. Run python3 merge-json-configuration-python.py < request.json.
  4. Compare stdout with the expected JSON. Exit 0 processes a valid request; invalid input exits 2 with empty stdout and a generic stderr message.

Limits to understand

  • The request must have exactly base and overlay, both objects. Maximum nesting is 64 open objects or arrays, counting the outer request object as level one.
  • Only corresponding objects merge recursively. Arrays, booleans, numbers and null replace prior values. Null is not a deletion marker; this custom policy differs from JSON Merge Patch (RFC 7396).
  • Duplicate keys, non-finite numbers and unpaired Unicode surrogates are rejected. Integers retain precision within the input byte bound; fractional and exponent-form values use Python floating-point precision.
  • The program explicitly disables the Python integer digit-conversion limit inside its isolated process; request size and sandbox resource limits still apply.
  • This does not validate an application schema, substitute environment variables, redact secrets or preserve whitespace, numeric spelling and original object key order.

Run it

python3 merge-json-configuration-python.py < request.json

Example input

{"base":{"db":{"host":"localhost","port":5432},"tags":["old"]},"overlay":{"db":{"port":5433},"tags":["new"]}}

Expected output

{"merged":{"db":{"host":"localhost","port":5433},"tags":["new"]}}
INSPECT THE SCRIPT

Inspect, copy and run the documented checks.

This browser preview builds code locally. It does not contact an API or run the code.

Default example ready.

Python example
import json
import math
import sys


MAX_BYTES = 20000
MAX_DEPTH = 64


def reject_constant(_):
    raise ValueError('invalid number')


def finite_float(text):
    value = float(text)
    if not math.isfinite(value):
        raise ValueError('invalid number')
    return value


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError('duplicate key')
        result[key] = value
    return result


def check_depth(text):
    depth = 0
    in_string = False
    escaped = False
    for char in text:
        if in_string:
            if escaped:
                escaped = False
            elif char == '\\':
                escaped = True
            elif char == '"':
                in_string = False
        elif char == '"':
            in_string = True
        elif char in '{[':
            depth += 1
            if depth > MAX_DEPTH:
                raise ValueError('too deep')
        elif char in '}]':
            depth -= 1
    # JSON parsing subsequently validates syntax and balanced delimiters.


def check_unicode(value):
    if isinstance(value, str):
        if any(0xD800 <= ord(char) <= 0xDFFF for char in value):
            raise ValueError('invalid Unicode')
    elif isinstance(value, dict):
        for key, child in value.items():
            check_unicode(key)
            check_unicode(child)
    elif isinstance(value, list):
        for child in value:
            check_unicode(child)


def merge(base, overlay):
    result = dict(base)
    for key, value in overlay.items():
        if key in base and isinstance(base[key], dict) and isinstance(value, dict):
            result[key] = merge(base[key], value)
        else:
            result[key] = value
    return result


def main():
    try:
        if len(sys.argv) != 1:
            raise ValueError('unexpected arguments')
        raw = sys.stdin.buffer.read(MAX_BYTES + 1)
        if len(raw) > MAX_BYTES:
            raise ValueError('too large')
        text = raw.decode('utf-8', errors='strict')
        check_depth(text)
        # Permit finite integers of any length within the input byte limit.
        sys.set_int_max_str_digits(0)
        data = json.loads(
            text,
            object_pairs_hook=unique_object,
            parse_float=finite_float,
            parse_constant=reject_constant,
        )
        check_unicode(data)
        if not isinstance(data, dict) or set(data) != {'base', 'overlay'}:
            raise ValueError('invalid outer object')
        if not isinstance(data['base'], dict) or not isinstance(data['overlay'], dict):
            raise ValueError('invalid configuration objects')
        output = json.dumps(
            {'merged': merge(data['base'], data['overlay'])},
            ensure_ascii=False,
            allow_nan=False,
            separators=(',', ':'),
        ).encode('utf-8')
    except Exception:
        sys.stderr.write('Error: invalid input.\n')
        return 2
    sys.stdout.buffer.write(output)
    return 0


if __name__ == '__main__':
    sys.exit(main())
What to verify after running
  • Run the documented example and compare its parsed JSON output.
  • Confirm invalid input exits 2 and does not echo request contents to stdout.
  • 32 independent CLI cases passed on the exact reviewed source in the pinned Python sandbox.

Request or format preview

Illustrative preview. No provider response, price or balance is fetched.

Change a setting to inspect the preview.

Official sources and related profiles

    Code license: MIT. Keep the license notice with your copy.

    Example version 1.0.0 · Documentation reviewed 2026-11-14.

    32 independent CLI cases passed in rootless Docker on the pinned Python 3.12 image, with 512 MiB RAM, 1 CPU and no network. Includes the documented example, malformed input, Unicode and the inclusive 20000-byte boundary. Other runtimes and all possible inputs have not been verified.