JSON Patch顺序执行实战:同一数组里移动元素,为什么目的下标要等删除以后再解释

10-08 6阅读

一份看板原来按 A、B、C、D 排列。客户端想把 A 移到下标二,提交了从 /cards/0 到 /cards/2 的 move。服务端如果先记住旧数组的“第二个位置”,再删除 A,很容易把结果排错。JSON Patch 的目的位置应在删除完成后的文档里重新解释。

JSON Patch顺序执行实战:同一数组里移动元素,为什么目的下标要等删除以后再解释

AI模型生成的概念示意图:A B C D经一次移动变为B C A D;不是软件运行截图。正文完整补丁还会追加E。

本文用 Python 标准库写一个教学解释器,执行 add、remove、replace、move、copy、test 六种操作。重点是操作顺序、JSON Pointer、数组插入以及失败时保住原文档;它处理本地数据,不连接数据库或网站,也不是可直接部署的 HTTP 接口。

先把补丁理解为一串动作

JSON Patch 的输入是操作数组,每一步都看见前一步的结果。它与用对象递归合并字段的 JSON Merge Patch 有不同合同。这里用 replace 把 note 设为 null,会保留该成员;删除必须明确写 remove。add 对已有对象成员会覆盖其值,对数组位置则插入并把后面的元素向右移。六种动作与错误规则见 RFC 6902。

本例先移动 A,得到 B、C、A、D;再把备注置空,并在尾部追加 E。因此完整程序打印的是 B、C、A、D、E。若配图只展示四张卡片移动,它说明的是第一步,不是整份补丁执行完的全部结果。

完整程序与实跑结果

将下列代码保存为 demo.py,运行 python3 demo.py。本次环境为 Linux、CPython 3.12.14,主程序退出码为零,标准错误为空。代码只依赖标准库;测试使用assert,请不要用python3 -O运行;用到的语法和接口可在 Python 3.10 及以上版本使用。

"""JSON Patch teaching interpreter. Python 3.10+, standard library only."""
from copy import deepcopy
from decimal import Decimal
import json
import re

ABSENT = object()  # A removed document, distinct from JSON null.
INDEX = re.compile(r"0|[1-9][0-9]*")
BAD_ESCAPE = re.compile(r"~(?![01])")


class PatchError(ValueError):
    pass


def strict_loads(text):
    def pairs(items):
        result = {}
        for key, value in items:
            if key in result:
                raise PatchError("duplicate JSON member")
            result[key] = value
        return result

    def invalid_number(text):
        raise PatchError("non-finite JSON number")

    if type(text) is not str or len(text) > 1_000_000:
        raise PatchError("expected at most 1000000 text characters")
    return json.loads(text, object_pairs_hook=pairs,
                      parse_float=Decimal, parse_constant=invalid_number)


def validate_tree(value, depth=0, seen=None):
    if depth > 64:
        raise PatchError("teaching implementation depth limit exceeded")
    kind = type(value)
    if seen is None:
        seen = set()
    if kind in (list, dict):
        if id(value) in seen:
            raise PatchError("JSON trees cannot share mutable container identities")
        seen.add(id(value))
    if value is None or kind in (str, bool, int):
        return
    if kind is Decimal and value.is_finite():
        return
    if kind is list:
        for item in value:
            validate_tree(item, depth + 1, seen)
        return
    if kind is dict and all(type(k) is str for k in value):
        for item in value.values():
            validate_tree(item, depth + 1, seen)
        return
    raise PatchError("expected a JSON tree using int/Decimal for numbers")


def pointer(text):
    if type(text) is not str or len(text) > 4096:
        raise PatchError("invalid or overlong pointer")
    if text == "":
        return []
    if not text.startswith("/") or BAD_ESCAPE.search(text):
        raise PatchError("invalid pointer syntax")
    return [part.replace("~1", "/").replace("~0", "~")
            for part in text[1:].split("/")]


def array_index(token, size, inserting=False):
    if token == "-" and inserting:
        return size
    if INDEX.fullmatch(token) is None:
        raise PatchError("invalid array index")
    # Reject an oversized index before converting a huge decimal integer.
    if len(token) > len(str(size)):
        raise PatchError("array index out of range")
    index = int(token)
    if index > size or (index == size and not inserting):
        raise PatchError("array index out of range")
    return index


def get(root, path):
    if root is ABSENT:
        raise PatchError("document does not exist")
    value = root
    for token in path:
        if type(value) is dict:
            if token not in value:
                raise PatchError("object member does not exist")
            value = value[token]
        elif type(value) is list:
            value = value[array_index(token, len(value))]
        else:
            raise PatchError("cannot descend through a scalar")
    return value


def put(root, path, value, replacing=False):
    if replacing:
        get(root, path)  # Replacement requires the exact target to exist.
    value = deepcopy(value)
    if not path:
        return value
    parent, token = get(root, path[:-1]), path[-1]
    if type(parent) is dict:
        parent[token] = value
    elif type(parent) is list:
        index = array_index(token, len(parent), inserting=not replacing)
        if replacing:
            parent[index] = value
        else:
            parent.insert(index, value)
    else:
        raise PatchError("target parent is not a container")
    return root


def remove(root, path):
    value = get(root, path)
    if not path:
        return ABSENT, value
    parent, token = get(root, path[:-1]), path[-1]
    if type(parent) is dict:
        del parent[token]
    else:
        parent.pop(array_index(token, len(parent)))
    return root, value


def equal_json(left, right):
    numeric = (int, Decimal)
    if type(left) in numeric and type(right) in numeric:
        return left == right
    if type(left) is not type(right):
        return False
    if type(left) is list:
        return len(left) == len(right) and all(
            equal_json(a, b) for a, b in zip(left, right))
    if type(left) is dict:
        return left.keys() == right.keys() and all(
            equal_json(left[k], right[k]) for k in left)
    return left == right


def apply_patch(document, operations):
    validate_tree(document)
    validate_tree(operations)
    if type(operations) is not list or len(operations) > 1000:
        raise PatchError("expected an array of at most 1000 operations")
    working = deepcopy(document)
    for step, operation in enumerate(operations):
        try:
            if type(operation) is not dict:
                raise PatchError("operation must be an object")
            name = operation.get("op")
            if type(name) is not str or name not in (
                    "add", "remove", "replace", "move", "copy", "test"):
                raise PatchError("unknown operation")
            if "path" not in operation:
                raise PatchError("missing path")
            path = pointer(operation["path"])
            if name in ("add", "replace", "test"):
                if "value" not in operation:
                    raise PatchError("missing value")
                value = operation["value"]
                if name == "test":
                    if not equal_json(get(working, path), value):
                        raise PatchError("test failed")
                else:
                    working = put(working, path, value, name == "replace")
            elif name == "remove":
                working, _ = remove(working, path)
            else:
                if "from" not in operation:
                    raise PatchError("missing from")
                source = pointer(operation["from"])
                value = get(working, source)
                if name == "move":
                    if len(source) < len(path) and path[:len(source)] == source:
                        raise PatchError("cannot move into own descendant")
                    if source == path:
                        continue
                    working, value = remove(working, source)
                working = put(working, path, value)
        except PatchError as error:
            raise PatchError(f"operation {step}: {error}") from error
    return working


def main():
    original = {"cards": ["A", "B", "C", "D"], "note": "keep"}
    changes = [
        {"op": "move", "from": "/cards/0", "path": "/cards/2"},
        {"op": "replace", "path": "/note", "value": None},
        {"op": "add", "path": "/cards/-", "value": "E"},
    ]
    changed = apply_patch(original, changes)
    print("new cards:", changed["cards"])
    print("note exists and is null:", "note" in changed and changed["note"] is None)
    print("original:", original)
    try:
        apply_patch(original, [
            {"op": "replace", "path": "/note", "value": "changed"},
            {"op": "test", "path": "/cards/0", "value": "Z"},
        ])
    except PatchError as error:
        print("rejected:", error)
    print("original after failure:", original)
    decimal_doc = strict_loads('{"n": 9007199254740993.0}')
    decimal_test = strict_loads(
        '[{"op":"test","path":"/n","value":9007199254740993}]')
    apply_patch(decimal_doc, decimal_test)
    print("exact decimal/integer test: passed")
    assert pointer("/~01") == ["~1"]
    assert pointer("/") == [""] and pointer("") == []
    assert not equal_json(True, 1)
    assert not equal_json([True], [1])
    copied = apply_patch({"a": {"x": [1]}}, [
        {"op": "copy", "from": "/a", "path": "/b"},
        {"op": "replace", "path": "/b/x/0", "value": 2},
    ])
    assert copied == {"a": {"x": [1]}, "b": {"x": [2]}}
    checks = 0
    for size in range(1, 9):
        for src in range(size):
            for dst in range(size):
                before = list(range(size))
                tail = before[:src] + before[src + 1:]
                expected = tail[:dst] + [src] + tail[dst:]
                result = apply_patch(before, [
                    {"op": "move", "from": f"/{src}", "path": f"/{dst}"}])
                assert result == expected and before == list(range(size))
                checks += 1
    print("exhaustive array moves:", checks)
    rejected = [
        ({}, [{"op": "add", "path": "/a/b", "value": 1}]),
        ({"a": None}, [{"op": "add", "path": "/a/b", "value": 1}]),
        ([1], [{"op": "add", "path": "/01", "value": 2}]),
        ([1], [{"op": "replace", "path": "/-", "value": 2}]),
        ([1, 2, 3], [{"op": "move", "from": "/0", "path": "/3"}]),
        ({"a": {}}, [{"op": "move", "from": "/a", "path": "/a/b"}]),
        ({}, [{"op": "replace", "path": "/a", "value": None}]),
        ({}, [{"op": "add", "path": "/~2", "value": 1}]),
        ({}, [{"op": "move", "from": "/a", "path": "/a"}]),
        ({"a": True}, [{"op": "test", "path": "/a", "value": 1}]),
    ]
    for doc, patch in rejected:
        before = deepcopy(doc)
        try:
            apply_patch(doc, patch)
        except PatchError:
            assert doc == before
        else:
            raise AssertionError("invalid patch accepted")
    print("boundary rejection cases:", len(rejected))


if __name__ == "__main__":
    main()

以下为实际标准输出,供核对使用:

new cards: ['B', 'C', 'A', 'D', 'E']
note exists and is null: True
original: {'cards': ['A', 'B', 'C', 'D'], 'note': 'keep'}
rejected: operation 1: test failed
original after failure: {'cards': ['A', 'B', 'C', 'D'], 'note': 'keep'}
exact decimal/integer test: passed
exhaustive array moves: 204
boundary rejection cases: 10

把路径拆成词元以后再做判断

空字符串路径指向整份文档,单个斜杠则指向名称为空的对象成员。路径中的 ~1 表示键名里的斜杠,~0 表示波浪号。代码先检查非法转义,再按这两个替换的顺序解码,确保 /~01 找到名为 ~1 的键,不会误找名为斜杠的键。相关语法见 RFC 6901。

JSON Patch 中的路径使用字符串形式,不是 URL 片段。因此 #/cards 被拒绝,/%2F 寻找字面键名 %2F,不会做百分号解码。普通字符串键也不会自动进行 Unicode 规范化,组合音符与预组合字符是否合并,是应用另一个层面的决定。

禁止把一个值移进自己的后代时,比较的是解码后的词元列表。/a 是 /a/b 的祖先,却不是 /ab 的祖先;直接做字符串 startswith 会误拦后一种合法移动。相同源与目标可以保持原样,但仍要先确认源存在,所以“把不存在的 /a 移到 /a”不会凭空成功。

数组下标属于当前状态

对 A、B、C、D 执行从零到二的移动,先取出 A,剩下 B、C、D;然后在当前下标二、也就是 D 前面插入 A。程序没有再对目的下标减一。若自行按旧数组位置修正,反而会改变协议表达的动作。

长度为三的数组删去一项后只剩两项,此时 add 的合法数字位置是零、一、二。将原下标零移到三会失败;若希望移到当前末尾,可以使用 -。代码只在插入时接受数组的 -,读取、替换和删除都要求一个实际存在的位置。

数组词元只接收规范的非负十进制写法,不能带前导零、加号、负号或空格。/01 在数组上无效,在对象上却可以是合法键名。array_index 因而只由已经确认的列表分支调用,不会提前把所有数字形状的对象键转成整数。

缺少末级成员与缺少父容器要分开

add 可以创建对象的最后一个成员,但它不负责补出中间路径。对空对象 add /prefs/theme 会失败;必须先建立 /prefs 对象,或者提交一整个带 theme 的 prefs 值。若 prefs 已经是 null、数字或布尔值,也不能直接向里面下钻。

replace 与 remove 更严格,目标本身必须存在。写 value: null 是提交了一个明确的值;操作对象完全没有 value 成员才是缺少参数。代码用成员存在性检查这两种状态,避免把合法置空误当成漏填。

未为当前动作定义的额外成员会被忽略,例如 add 里的备注字段。未知 op 则必须报错。解析文本时还会拒绝重复的对象键,避免两个 op 或两个 path 被普通字典解析悄悄覆盖后,失去原始请求的歧义。

copy复制值,不能给两处留下同一份可变对象

JSON 文档没有 Python 式的共享列表引用。copy 一段对象以后,再修改新位置里的数组,不应连带改变源位置。put 对加入的值做深复制,既隔开文档中的两处位置,也避免后续改动污染调用方保存的补丁对象。

因此把 /a 复制到 /a/child 可以得到一个有限副本;它不会让 child 回指 a 并制造循环。输入若是手工组装的 Python 对象图,验证器还拒绝共享的可变容器身份和过深嵌套。用 strict_loads 从普通 JSON 文本解析出来的数据,本来就没有这些引用关系。

test需要JSON的相等规则

Python 中 True == 1 为真,但两者属于不同 JSON 类型,所以不能直接把 Python 的递归相等比较当作 test。equal_json 先单独识别数字类型,再比较其他类型;数组保持位置关系,对象按键集合及对应值比较,不把成员排列顺序当成差异。

数字还涉及解析精度。本例用 int 保存整数字面量,用 Decimal 保存带小数点或指数的字面量,使 9007199254740993.0 不先舍入到另一个二进制浮点数。于是它能与相同数值的整数通过 test,却不会与少一的整数混同。解析钩子、默认重复键和非有限数行为可查 Python json 官方文档。

这个树接口明确不接收手工传入的 float;调用方应使用给出的解析入口。它返回的树可能含 Decimal,不能直接用默认 json.dumps 输出,也不要为省事转回 float。若要提供网络响应,应选用并测试能保留既定数值语义的序列化层。本文演示只打印不含 Decimal 的结果结构,另外用断言检验精确数字。

失败后原文档为何仍然完整

解释器先深复制 document,所有动作只修改 working。第二步 test 失败时,函数抛出带从零开始操作编号的异常,working 没有交回调用者;原来的备注仍然是 keep。即使 move 已经在工作副本里删除源,而目标随后被判定无效,也不会改坏外部原文档。

这实现的是本地函数的“成功返回新值,失败保留旧值”。它不等于数据库事务,也没有解决两个编辑者并发保存的问题。接到 HTTP PATCH 时,还需把读取版本、完整补丁计算、业务校验与提交放进合适的事务或条件更新中;只在内存里 test 旧版本,随后无条件覆盖数据库,仍可能丢掉别人刚写入的内容。

根路径也有明确结果:replace 根为 null,返回的是 None;remove 根则返回专用标记 ABSENT,表示已没有文档。ABSENT 是本教程接口对“根被移除”的表示约定,不是 JSON 值,不能序列化成 null。存储适配层必须自己约定如何表达这一状态;同一补丁内随后 add 根,可以重新建立文档。

验证覆盖到哪里

文中程序枚举长度一到八的数组全部源、目标组合,共204种移动,比较删除后再插入的独立预期列表,并确认输入没有改变。十个拒绝样本覆盖缺父节点、null父节点、非规范下标、追加位置误用于replace、删除后越界、移入后代、缺少目标、非法转义、不存在的同址移动以及布尔值与数字混比。

另一个本地测试文件运行了13组测试,包含全部六种操作组合、空键与带斜杠键、根删除及重建、copy独立性、未知扩展成员、重复键和非有限数拒绝,全部通过。它们验证的是这份教学实现和所列边界,没有测出生产吞吐量或证明任意输入都可安全处理。

深复制需要与文档大小相关的时间和内存;数组中间的插入、删除也需要移动后续元素。连续 copy 大子树还可能让结果迅速膨胀。代码已有文本字符数、操作数、路径长度和初始深度的教学上限,但真实接口仍需要解析前后资源配额、字段授权、结果模式校验和并发控制,不能仅靠“符合JSON Patch语法”决定是否允许更新。

资料与代码核对日期:2026年10月7日。示例数据、实现结构和解释独立组织;没有执行任何生产配置修改。

参考资料


文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。