python-json-patch Documentation

Similar documents
python-json-pointer Documentation

pysharedutils Documentation

FIQL Parser. Release 0.15

redis-lua Documentation

solrq Documentation Release Michał Jaworski

Beyond Blocks: Python Session #1

doubles Documentation

prompt Documentation Release Stefan Fischer

Internet Engineering Task Force (IETF) ISSN: April 2013

django-auditlog Documentation

linkgrabber Documentation

Archer Documentation. Release 0.1. Praekelt Dev

pyprika Documentation

bzz Documentation Release Rafael Floriano and Bernardo Heynemann

Tagalog Documentation

Dogeon Documentation. Release Lin Ju

CS Programming Languages: Python

django-conduit Documentation

Requests Mock Documentation

pingparsing Documentation

bottle-rest Release 0.5.0

Argparse Tutorial Release 2.7.9

Lecture 1: Introduction to Python

python-docker-machine Documentation

Connexion Documentation

g-pypi Documentation Release 0.3 Domen Kožar

WordEmbeddingLoader Documentation

yarl Documentation Release Andrew Svetlov

asn1tools Documentation

maya-cmds-help Documentation

djangotribune Documentation

nucleon Documentation

pyautocad Documentation

Pypeline Documentation

Kaiso Documentation. Release 0.1-dev. onefinestay

logstack Documentation

MongoTor Documentation

python-anyvcs Documentation

cloudns Documentation

pybdg Documentation Release 1.0.dev2 Outernet Inc

ArangoDB Python Driver Documentation

[301] JSON. Tyler Caraza-Harter

Django-CSP Documentation

Traits CLI Documentation

CS115 - Module 3 - Booleans, Conditionals, and Symbols

Avpy Documentation. Release sydh

Accelerating Information Technology Innovation

certbot-dns-rfc2136 Documentation

Pymixup Documentation

Json Extensions Documentation

streamio Documentation

JSON. Version 6.6. Eli Barzilay and Dave Herman. July 22, 2016

pymemcache Documentation

CS61A Notes Week 13: Interpreters

Accelerating Information Technology Innovation

NeoJSON. 1.1 An Introduction to JSON

tld Documentation Release 0.9 Artur Barseghyan

Sherlock Documentation

Celery-RabbitMQ Documentation

yaml Documentation Release dev Anthon van der Neut

CS1 Lecture 3 Jan. 18, 2019

Friday, 11 April 14. Advanced methods for creating decorators Graham Dumpleton PyCon US - April 2014

dicompyler-core Documentation

Armide Documentation. Release Kyle Mayes

Connexion Sqlalchemy Utils Documentation

Python Overpass API Documentation

Shouldly Documentation

sqlalchemy-redshift Documentation

petfinder-api Documentation

CS1 Lecture 3 Jan. 22, 2018

Jarek Szlichta

python-aspectlib Release 0.5.0

json2xls Documentation

MEIN 50010: Python Flow Control

Packtools Documentation

validictory Documentation

Intro. Classes & Inheritance

django-dynamic-db-router Documentation

cursesmenu Documentation

django-slim Documentation

Queries Documentation

pybtsync Documentation


Torndb Release 0.3 Aug 30, 2017

TastyTopping Documentation

databuild Documentation

Ensure Documentation. Release Andrey Kislyuk

kvkit Documentation Release 0.1 Shuhao Wu

eoddata-client Documentation

Uranium Documentation

JSONRPC Documentation

CS 4218 Software Testing and Debugging Ack: Tan Shin Hwei for project description formulation

BibtexParser Documentation

dql Release gadaccee-dirty

my $reply = $term->get_reply( prompt => 'What is your favourite colour?', choices => [qw blue red green ], default => blue, );

PyZabbixObj Documentation

xmljson Documentation

nptdms Documentation Release Adam Reeve

Chapter 9: Dealing with Errors

picrawler Documentation

Transcription:

python-json-patch Documentation Release 1.21 Stefan Kögl Jan 16, 2018

Contents 1 Tutorial 3 1.1 Creating a Patch............................................. 3 1.2 Applying a Patch............................................. 4 2 The jsonpatch module 5 3 Commandline Utilities 9 3.1 jsondiff................................................ 9 3.2 jsonpatch............................................... 10 4 Indices and tables 13 Python Module Index 15 i

ii

python-json-patch is a Python library for applying JSON patches (RFC 6902). Python 2.7 and 3.4+ are supported. Tests are run on both CPython and PyPy. Contents Contents 1

2 Contents

CHAPTER 1 Tutorial Please refer to RFC 6902 for the exact patch syntax. 1.1 Creating a Patch Patches can be created in two ways. One way is to explicitly create a JsonPatch object from a list of operations. For convenience, the method JsonPatch.from_string() accepts a string, parses it and constructs the patch object from it. >>> import jsonpatch >>> patch = jsonpatch.jsonpatch([ {'op': 'add', 'path': '/foo', 'value': 'bar'}, {'op': 'add', 'path': '/baz', 'value': [1, 2, 3]}, {'op': 'remove', 'path': '/baz/1'}, {'op': 'test', 'path': '/baz', 'value': [1, 3]}, {'op': 'replace', 'path': '/baz/0', 'value': 42}, {'op': 'remove', 'path': '/baz/1'}, ]) # or equivalently >>> patch = jsonpatch.jsonpatch.from_string('[{"op": "add",...}]') Another way is to diff two objects. >>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]} >>> dst = {'baz': 'qux', 'numbers': [1, 4, 7]} >>> patch = jsonpatch.jsonpatch.from_diff(src, dst) # or equivalently >>> patch = jsonpatch.make_patch(src, dst) 3

1.2 Applying a Patch A patch is always applied to an object. >>> doc = {} >>> result = patch.apply(doc) {'foo': 'bar', 'baz': [42]} The apply method returns a new object as a result. If in_place=true the object is modified in place. If a patch is only used once, it is not necessary to create a patch object explicitly. >>> obj = {'foo': 'bar'} # from a patch string >>> patch = '[{"op": "add", "path": "/baz", "value": "qux"}]' >>> res = jsonpatch.apply_patch(obj, patch) # or from a list >>> patch = [{'op': 'add', 'path': '/baz', 'value': 'qux'}] >>> res = jsonpatch.apply_patch(obj, patch) 4 Chapter 1. Tutorial

CHAPTER 2 The jsonpatch module Apply JSON-Patches (RFC 6902) class jsonpatch.addoperation(operation) Adds an object property or an array element. class jsonpatch.copyoperation(operation) Copies an object property or an array element to a new location exception jsonpatch.invalidjsonpatch Raised if an invalid JSON Patch is created class jsonpatch.jsonpatch(patch) A JSON Patch is a list of Patch Operations. >>> patch = JsonPatch([... {'op': 'add', 'path': '/foo', 'value': 'bar'},... {'op': 'add', 'path': '/baz', 'value': [1, 2, 3]},... {'op': 'remove', 'path': '/baz/1'},... {'op': 'test', 'path': '/baz', 'value': [1, 3]},... {'op': 'replace', 'path': '/baz/0', 'value': 42},... {'op': 'remove', 'path': '/baz/1'},... ]) >>> doc = {} >>> result = patch.apply(doc) >>> expected = {'foo': 'bar', 'baz': [42]} >>> result == expected True JsonPatch object is iterable, so you could easily access to each patch statement in loop: >>> lpatch = list(patch) >>> expected = {'op': 'add', 'path': '/foo', 'value': 'bar'} >>> lpatch[0] == expected True >>> lpatch == patch.patch True 5

Also JsonPatch could be converted directly to bool if it contains any operation statements: >>> bool(patch) True >>> bool(jsonpatch([])) False This behavior is very handy with make_patch() to write more readable code: >>> old = {'foo': 'bar', 'numbers': [1, 3, 4, 8]} >>> new = {'baz': 'qux', 'numbers': [1, 4, 7]} >>> patch = make_patch(old, new) >>> if patch:... # document have changed, do something useful... patch.apply(old) {...} apply(obj, in_place=false) Applies the patch to given object. Parameters obj (dict) Document object. in_place (bool) Tweaks way how patch would be applied - directly to specified obj or to his copy. Returns Modified obj. classmethod from_diff(src, dst, optimization=true) Creates JsonPatch instance based on comparing of two document objects. Json patch would be created for src argument against dst one. Parameters src (dict) Data source document object. dst (dict) Data source document object. Returns JsonPatch instance. >>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]} >>> dst = {'baz': 'qux', 'numbers': [1, 4, 7]} >>> patch = JsonPatch.from_diff(src, dst) >>> new = patch.apply(src) >>> new == dst True classmethod from_string(patch_str) Creates JsonPatch instance from string source. Parameters patch_str (str) JSON patch as raw string. Returns JsonPatch instance. to_string() Returns patch set as JSON string. exception jsonpatch.jsonpatchconflict Raised if patch could not be applied due to conflict situation such as: - attempt to add object key then it already exists; - attempt to operate with nonexistence object key; - attempt to insert value to array at position beyond of it size; - etc. 6 Chapter 2. The jsonpatch module

exception jsonpatch.jsonpatchexception Base Json Patch exception exception jsonpatch.jsonpatchtestfailed A Test operation failed class jsonpatch.moveoperation(operation) Moves an object property or an array element to new location. class jsonpatch.patchoperation(operation) A single operation inside a JSON Patch. apply(obj) Abstract method that applies patch operation to specified object. class jsonpatch.removeoperation(operation) Removes an object property or an array element. class jsonpatch.replaceoperation(operation) Replaces an object property or an array element by new value. class jsonpatch.testoperation(operation) Test value by specified location. jsonpatch.apply_patch(doc, patch, in_place=false) Apply list of patches to specified json document. Parameters doc (dict) Document object. patch (list or str) JSON patch as list of dicts or raw JSON-encoded string. in_place (bool) While True patch will modify target document. By default patch will be applied to document copy. Returns Patched document object. Return type dict >>> doc = {'foo': 'bar'} >>> patch = [{'op': 'add', 'path': '/baz', 'value': 'qux'}] >>> other = apply_patch(doc, patch) >>> doc is not other True >>> other == {'foo': 'bar', 'baz': 'qux'} True >>> patch = [{'op': 'add', 'path': '/baz', 'value': 'qux'}] >>> apply_patch(doc, patch, in_place=true) == {'foo': 'bar', 'baz': 'qux'} True >>> doc == other True jsonpatch.make_patch(src, dst) Generates patch by comparing of two document objects. Actually is a proxy to JsonPatch.from_diff() method. Parameters src (dict) Data source document object. dst (dict) Data source document object. 7

>>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]} >>> dst = {'baz': 'qux', 'numbers': [1, 4, 7]} >>> patch = make_patch(src, dst) >>> new = patch.apply(src) >>> new == dst True jsonpatch.multidict(ordered_pairs) Convert duplicate keys values to lists. 8 Chapter 2. The jsonpatch module

CHAPTER 3 Commandline Utilities The JSON patch package contains the commandline utilities jsondiff and jsonpatch. 3.1 jsondiff The program jsondiff can be used to create a JSON patch by comparing two JSON files usage: jsondiff [-h] [--indent INDENT] [-v] FILE1 FILE2 Diff two JSON files positional arguments: FILE1 FILE2 optional arguments: -h, --help show this help message and exit --indent INDENT Indent output by n spaces -v, --version show program's version number and exit 3.1.1 Example # inspect JSON files $ cat a.json { "a": [1, 2], "b": 0 } $ cat b.json { "a": [1, 2, 3], "c": 100 } # show patch in "dense" representation $ jsondiff a.json b.json [{"path": "/a/2", "value": 3, "op": "add"}, {"path": "/b", "op": "remove"}, {"path": "/c", "value": 100, "op": "add"}] 9

# show patch with some indentation $ jsondiff a.json b.json --indent=2 [ { "path": "/a/2", "value": 3, "op": "add" }, { "path": "/b", "op": "remove" }, { "path": "/c", "value": 100, "op": "add" } ] 3.2 jsonpatch The program jsonpatch is used to apply JSON patches on JSON files. usage: jsonpatch [-h] [--indent INDENT] [-v] ORIGINAL PATCH Apply a JSON patch on a JSON files positional arguments: ORIGINAL Original file PATCH Patch file optional arguments: -h, --help show this help message and exit --indent INDENT Indent output by n spaces -v, --version show program's version number and exit 3.2.1 Example # create a patch $ jsondiff a.json b.json > patch.json # show the result after applying a patch $ jsonpatch a.json patch.json {"a": [1, 2, 3], "c": 100} $ jsonpatch a.json patch.json --indent=2 { "a": [ 1, 2, 3 ], 10 Chapter 3. Commandline Utilities

} "c": 100 # pipe result into new file $ jsonpatch a.json patch.json --indent=2 > c.json # c.json now equals b.json $ jsondiff b.json c.json [] 3.2. jsonpatch 11

12 Chapter 3. Commandline Utilities

CHAPTER 4 Indices and tables genindex modindex search 13

14 Chapter 4. Indices and tables

Python Module Index j jsonpatch, 5 15

16 Python Module Index

Index A AddOperation (class in jsonpatch), 5 apply() (jsonpatch.jsonpatch method), 6 apply() (jsonpatch.patchoperation method), 7 apply_patch() (in module jsonpatch), 7 C CopyOperation (class in jsonpatch), 5 F from_diff() (jsonpatch.jsonpatch class method), 6 from_string() (jsonpatch.jsonpatch class method), 6 I InvalidJsonPatch, 5 J JsonPatch (class in jsonpatch), 5 jsonpatch (module), 5 JsonPatchConflict, 6 JsonPatchException, 6 JsonPatchTestFailed, 7 M make_patch() (in module jsonpatch), 7 MoveOperation (class in jsonpatch), 7 multidict() (in module jsonpatch), 8 P PatchOperation (class in jsonpatch), 7 R RemoveOperation (class in jsonpatch), 7 ReplaceOperation (class in jsonpatch), 7 T TestOperation (class in jsonpatch), 7 to_string() (jsonpatch.jsonpatch method), 6 17