Answer A: Anthropic Claude Opus 4.8
import copy
class JsonPatchError(Exception):
"""Raised when a JSON Patch operation is invalid or fails."""
pass
def _unescape_token(token):
# Validate and decode a single JSON Pointer reference token.
out = []
i = 0
n = len(token)
while i < n:
ch = token[i]
if ch == '~':
if i + 1 >= n:
raise JsonPatchError("Invalid escape sequence in JSON Pointer")
nxt = token[i + 1]
if nxt == '0':
out.append('~')
elif nxt == '1':
out.append('/')
else:
raise Jso...
Show Full Answer ▼
import copy
class JsonPatchError(Exception):
"""Raised when a JSON Patch operation is invalid or fails."""
pass
def _unescape_token(token):
# Validate and decode a single JSON Pointer reference token.
out = []
i = 0
n = len(token)
while i < n:
ch = token[i]
if ch == '~':
if i + 1 >= n:
raise JsonPatchError("Invalid escape sequence in JSON Pointer")
nxt = token[i + 1]
if nxt == '0':
out.append('~')
elif nxt == '1':
out.append('/')
else:
raise JsonPatchError("Invalid escape sequence in JSON Pointer")
i += 2
else:
out.append(ch)
i += 1
return ''.join(out)
def _parse_pointer(path):
if not isinstance(path, str):
raise JsonPatchError("JSON Pointer must be a string")
if path == "":
return []
if not path.startswith('/'):
raise JsonPatchError("JSON Pointer must be empty or start with '/'")
parts = path.split('/')[1:]
return [_unescape_token(p) for p in parts]
def _is_valid_array_index(token, allow_dash=False):
if allow_dash and token == '-':
return True
if token == '0':
return True
if not token:
return False
if not token.isdigit():
return False
if token[0] == '0':
return False
return True
def _resolve_parent(doc, tokens, allow_dash_last=False):
# Navigate to the container that holds the final token.
# Returns (parent, final_token).
if not tokens:
raise JsonPatchError("Path refers to whole document; no parent")
current = doc
for tok in tokens[:-1]:
current = _descend(current, tok, allow_dash=False)
return current, tokens[-1]
def _descend(container, token, allow_dash=False):
if isinstance(container, dict):
if token not in container:
raise JsonPatchError("Object key not found: %r" % (token,))
return container[token]
elif isinstance(container, list):
if not _is_valid_array_index(token, allow_dash=allow_dash):
raise JsonPatchError("Invalid array index: %r" % (token,))
if token == '-':
raise JsonPatchError("Cannot descend into '-' on array")
idx = int(token)
if idx < 0 or idx >= len(container):
raise JsonPatchError("Array index out of range: %d" % idx)
return container[idx]
else:
raise JsonPatchError("Cannot navigate into non-container value")
def _get_value(doc, tokens):
current = doc
for tok in tokens:
current = _descend(current, tok, allow_dash=False)
return current
def _do_add(doc, tokens, value):
if not tokens:
return value
parent, last = _resolve_parent(doc, tokens, allow_dash_last=True)
if isinstance(parent, dict):
if last == '-':
raise JsonPatchError("'-' is not valid for object add")
parent[last] = value
elif isinstance(parent, list):
if not _is_valid_array_index(last, allow_dash=True):
raise JsonPatchError("Invalid array index for add: %r" % (last,))
if last == '-':
parent.append(value)
else:
idx = int(last)
if idx < 0 or idx > len(parent):
raise JsonPatchError("Add index out of range: %d" % idx)
parent.insert(idx, value)
else:
raise JsonPatchError("Cannot add into non-container value")
return doc
def _do_remove(doc, tokens):
if not tokens:
raise JsonPatchError("Cannot remove whole document")
parent, last = _resolve_parent(doc, tokens)
if isinstance(parent, dict):
if last not in parent:
raise JsonPatchError("Cannot remove nonexistent key: %r" % (last,))
del parent[last]
elif isinstance(parent, list):
if not _is_valid_array_index(last, allow_dash=False):
raise JsonPatchError("Invalid array index for remove: %r" % (last,))
idx = int(last)
if idx < 0 or idx >= len(parent):
raise JsonPatchError("Remove index out of range: %d" % idx)
del parent[idx]
else:
raise JsonPatchError("Cannot remove from non-container value")
return doc
def _do_replace(doc, tokens, value):
if not tokens:
return value
parent, last = _resolve_parent(doc, tokens)
if isinstance(parent, dict):
if last not in parent:
raise JsonPatchError("Cannot replace nonexistent key: %r" % (last,))
parent[last] = value
elif isinstance(parent, list):
if not _is_valid_array_index(last, allow_dash=False):
raise JsonPatchError("Invalid array index for replace: %r" % (last,))
idx = int(last)
if idx < 0 or idx >= len(parent):
raise JsonPatchError("Replace index out of range: %d" % idx)
parent[idx] = value
else:
raise JsonPatchError("Cannot replace in non-container value")
return doc
def _deep_equal(a, b):
# Exact type-aware equality. Disallow bool/number cross matches.
if isinstance(a, bool) or isinstance(b, bool):
if type(a) is not type(b):
return False
return a == b
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
return a == b
if type(a) is not type(b):
return False
if a is None:
return b is None
if isinstance(a, str):
return a == b
if isinstance(a, list):
if len(a) != len(b):
return False
return all(_deep_equal(x, y) for x, y in zip(a, b))
if isinstance(a, dict):
if set(a.keys()) != set(b.keys()):
return False
return all(_deep_equal(a[k], b[k]) for k in a)
return a == b
def _is_prefix(prefix_tokens, tokens):
if len(prefix_tokens) > len(tokens):
return False
return tokens[:len(prefix_tokens)] == prefix_tokens
_REQUIRED_FIELDS = {
"add": {"op", "path", "value"},
"remove": {"op", "path"},
"replace": {"op", "path", "value"},
"move": {"op", "path", "from"},
"copy": {"op", "path", "from"},
"test": {"op", "path", "value"},
}
def _validate_op_fields(operation):
if not isinstance(operation, dict):
raise JsonPatchError("Operation must be a dict")
if "op" not in operation:
raise JsonPatchError("Operation missing 'op' field")
op = operation["op"]
if op not in _REQUIRED_FIELDS:
raise JsonPatchError("Unknown operation: %r" % (op,))
required = _REQUIRED_FIELDS[op]
actual = set(operation.keys())
if actual != required:
raise JsonPatchError("Operation %r has invalid fields" % (op,))
return op
def apply_json_patch(document, patch):
if not isinstance(patch, list):
raise JsonPatchError("Patch must be a list of operations")
# Work on a deep copy so the original is never mutated.
working = copy.deepcopy(document)
for operation in patch:
op = _validate_op_fields(operation)
if op == "add":
tokens = _parse_pointer(operation["path"])
working = _do_add(working, tokens, copy.deepcopy(operation["value"]))
elif op == "remove":
tokens = _parse_pointer(operation["path"])
working = _do_remove(working, tokens)
elif op == "replace":
tokens = _parse_pointer(operation["path"])
working = _do_replace(working, tokens, copy.deepcopy(operation["value"]))
elif op == "move":
from_tokens = _parse_pointer(operation["from"])
path_tokens = _parse_pointer(operation["path"])
if _is_prefix(from_tokens, path_tokens) and from_tokens != path_tokens:
raise JsonPatchError("Cannot move into one of its own descendants")
value = _get_value(working, from_tokens)
value = copy.deepcopy(value)
working = _do_remove(working, from_tokens)
working = _do_add(working, path_tokens, value)
elif op == "copy":
from_tokens = _parse_pointer(operation["from"])
path_tokens = _parse_pointer(operation["path"])
value = _get_value(working, from_tokens)
value = copy.deepcopy(value)
working = _do_add(working, path_tokens, value)
elif op == "test":
tokens = _parse_pointer(operation["path"])
current = _get_value(working, tokens)
if not _deep_equal(current, operation["value"]):
raise JsonPatchError("Test operation failed")
return working
Result
Winning Votes
3 / 3
Average Score
Total Score
Overall Comments
Answer A is a well-crafted implementation that correctly handles all six JSON Patch operations with careful attention to edge cases. Key strengths include: a proper _deep_equal function that correctly distinguishes booleans from integers (critical for the test operation), token-level descendant checking for the move operation using _is_prefix, correct ~ escape validation in _unescape_token, exact field validation using the _REQUIRED_FIELDS dict, and proper atomicity via deep-copying before any mutations. The code is well-organized with clear helper functions and is practically reliable.
View Score Details ▼
Correctness
Weight 35%Answer A correctly implements all six operations with careful validation. The _deep_equal function properly handles bool/int type distinction, which is critical for the test operation. The move operation correctly checks for descendant paths using token-level comparison. The _unescape_token function correctly validates that ~ is only followed by 0 or 1. Array index validation correctly rejects leading zeros. The atomicity is preserved by deep-copying the document before any mutations. One minor issue: in the move operation, moving a path to itself (from_tokens == path_tokens) is not explicitly handled as a no-op, but the code would still work (remove then add back). Overall very solid correctness.
Completeness
Weight 20%Answer A implements all six required operations (add, remove, replace, move, copy, test), handles root document replacement, validates JSON Pointer syntax including invalid ~ sequences, validates array indices including leading zeros, validates operation fields exactly (no extra, no missing), handles the '-' token for array append, and deep-copies values appropriately. The _REQUIRED_FIELDS dict ensures exact field validation. All edge cases mentioned in the spec are addressed.
Code Quality
Weight 20%Answer A is well-structured with clear helper functions, each with a single responsibility. The _REQUIRED_FIELDS dict is an elegant approach to field validation. The code is readable and maintainable. The _deep_equal function is carefully implemented. The _is_prefix function for move validation is clean. Minor issue: the code duplicates some logic between _do_add, _do_remove, _do_replace rather than using a shared traversal helper, but this is acceptable for clarity.
Practical Value
Weight 15%Answer A is practically very useful. It correctly handles all the edge cases that matter in real JSON Patch usage, including the bool/int distinction in test operations, proper token-level descendant checking for move, and correct ~ escape validation. The atomicity guarantee is properly implemented. The code would work correctly in production scenarios.
Instruction Following
Weight 10%Answer A follows all instructions: uses Python 3.11, implements apply_json_patch(document, patch), defines JsonPatchError, uses only standard library (copy module), does not mutate original document, raises JsonPatchError for invalid operations, handles all six operations, validates JSON Pointer syntax, handles all specified edge cases. The function signature and class name match exactly.
Total Score
Overall Comments
Answer A provides a robust and largely correct implementation of JSON Patch. Its JSON Pointer parsing, array index validation, and `test` operation's deep equality logic are particularly strong and adhere well to the specification. The code is well-structured and readable, with clear separation of concerns into helper functions. The main drawback is a semantic error in the `move` operation, where it deep-copies the value instead of moving the reference, which deviates from standard JSON Patch behavior.
View Score Details ▼
Correctness
Weight 35%Answer A provides a highly correct implementation. Its JSON Pointer parsing for escape sequences is robust, and the `_deep_equal` function for the `test` operation correctly implements the specified type-aware equality. The only notable correctness issue is that the `move` operation deep-copies the value instead of moving the reference, which is a semantic deviation from standard JSON Patch.
Completeness
Weight 20%Answer A fully implements all six required JSON Patch operations (add, remove, replace, move, copy, test), the custom `JsonPatchError` exception, and all specified JSON Pointer parsing rules. All features requested in the prompt are present.
Code Quality
Weight 20%The code in Answer A is well-structured with clear, focused helper functions. Variable names are descriptive, and the logic is generally explicit rather than relying on broad exception handling. The `_deep_equal` function is a good example of clear, robust logic. This contributes to high readability and maintainability.
Practical Value
Weight 15%Answer A provides a highly functional and reliable JSON Patch implementation. Its robust parsing and correct `test` operation make it suitable for practical use, despite the minor semantic deviation in the `move` operation. The atomicity guarantee is also well-implemented.
Instruction Following
Weight 10%Answer A follows almost all instructions precisely, including the custom exception, non-mutation, all operations, JSON Pointer rules (unescaping, leading zeros, array index rules, '-' for add), deep equality for `test`, and exact field validation for operations. The only minor deviation is the deep-copying behavior in the `move` operation, which is not standard JSON Patch semantics.
Total Score
Overall Comments
Answer A is a strong, runnable implementation with clear helper functions, proper deep-copying of the original document, exact operation field validation, good JSON Pointer escape validation, robust array index handling, and support for all required operations. Its main weaknesses are edge cases: it rejects adding an object member named '-' even though '-' should only be special for arrays, it rejects root removal and root move cases, and a non-string unhashable op value could escape as a TypeError instead of JsonPatchError. Overall it is substantially correct and maintainable.
View Score Details ▼
Correctness
Weight 35%Mostly correct across all operations, with strong pointer parsing, array index validation, atomicity relative to the original document, and deep-copy behavior. It loses points for rejecting object add to key '-', rejecting root move/removal cases, and potentially raising TypeError rather than JsonPatchError for an unhashable op value.
Completeness
Weight 20%Implements all six required operations, exact field sets, JSON Pointer decoding, array bounds and leading-zero rules, root add/replace, move descendant rejection, and copy deep-copying. Completeness is reduced by a few edge cases around '-' as an object key and root move/removal behavior.
Code Quality
Weight 20%Well-structured code with focused helpers for parsing, navigation, mutation, equality, and validation. The implementation is easy to follow and avoids relying on accidental Python exceptions in most places, though there is a small unused parameter and a few edge validations are imperfect.
Practical Value
Weight 15%Would be reliable in most practical JSON Patch use cases, protects the original input well, and provides deterministic JsonPatchError failures for nearly all malformed patches. The remaining issues are relatively uncommon edge cases.
Instruction Following
Weight 10%Closely follows the prompt by providing Python 3.11-compatible code, the requested function and exception, standard-library-only implementation, all supported operations, no CLI, and strong non-mutation of the original document. Minor deviations remain on edge-case path semantics and some error wrapping.