Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: create_parents for add operations #32

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ The module `json_patch` takes the following options:
| `src` | The path to a file containing JSON | |
| `dest` | The path to an optional output file to write the patched JSON (default is to overwrite `src` file) | |
| `operations` | A list of valid operations to perform against the given JSON file | See [RFC 6902](https://tools.ietf.org/html/rfc6902#section-4) |
| `create_parents` | For add operations, create any parent objects/arrays in the JSON-Pointer which do not yet exist (against Section 4.1 of RFC6902) (default: `no`) | `yes`/`no` |
| `backup` | Backup the JSON file (the one that will be overwritten) before editing (default: `no`) | `yes`/`no` |
| `unsafe_writes` | Allow Ansible to fall back to unsafe (i.e. non-atomic) methods of writing files (default: `no`) | `yes`/`no` |
| `pretty` | Write JSON output in human-readable format | `yes`/`no` |
Expand Down
42 changes: 33 additions & 9 deletions json_patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@
- A list of operations to perform on the JSON document
required: True
type: list
create_parents:
description:
- For add operations, create any parent objects/arrays in the JSON-Pointer which do not yet exist (against Section 4.1 of RFC6902)
required: False
type: bool
backup:
description:
- Copy the targeted file to a backup prior to patch
Expand Down Expand Up @@ -233,9 +238,11 @@ def __init__(self, module):
else:
self.module.fail_json(msg="invalid option for 'create_type': %s" % self.create_type)

self.create_parents = bool(self.module.params.get('create_parents'))

self.operations = self.module.params['operations']
try:
self.patcher = JSONPatcher(self.json_doc, *self.operations)
self.patcher = JSONPatcher(self.json_doc, self.create_parents, *self.operations)
except Exception as e:
self.module.fail_json(msg=str(e))

Expand Down Expand Up @@ -292,12 +299,13 @@ def write(self):
class JSONPatcher(object):
"""Patch JSON documents according to RFC 6902."""

def __init__(self, json_doc, *operations):
def __init__(self, json_doc, create_parents, *operations):
try:
self.obj = json.loads(json_doc) # let this fail if it must
except (ValueError, TypeError):
raise Exception("invalid JSON found")
self.operations = operations
self.create_parents = create_parents

# validate all operations
for op in self.operations:
Expand Down Expand Up @@ -336,6 +344,8 @@ def patch(self):
patch['from_path'] = patch['from']
del patch['from']

patch['create_parents'] = self.create_parents

# attach object to patch operation (helpful for recursion)
patch['obj'] = self.obj
new_obj, changed, tested = getattr(self, op)(**patch)
Expand Down Expand Up @@ -370,7 +380,7 @@ def _get(self, path, obj, **discard):
return next_obj

# https://tools.ietf.org/html/rfc6902#section-4.1
def add(self, path, value, obj, **discard):
def add(self, path, value, obj, create_parents, **discard):
"""Perform an 'add' operation."""
chg = False
path = path.lstrip('/')
Expand Down Expand Up @@ -403,9 +413,23 @@ def add(self, path, value, obj, **discard):
try:
next_obj = obj[path]
except KeyError:
raise PathError("could not find '%s' member in JSON object" % path)
obj[path], chg, _ = self.add(remaining, value, next_obj)
next_path = elements[1]
if not create_parents or (next_path.isdigit() and next_path != "0"):
raise PathError("could not find '%s' member in JSON object" % path)
# Create the parent
if next_path in ["0", "-"]:
next_obj = obj[path] = []
else:
next_obj = obj[path] = {}
obj[path], chg, _ = self.add(remaining, value, next_obj, create_parents)
elif isinstance(obj, list):
if create_parents:
if path == "-" or (len(obj) == 0 and path == "0"):
if elements[1] in ["0", "-"]:
obj.append([])
else:
obj.append({})
path = str(len(obj) - 1)
if not path.isdigit():
raise PathError("'%s' is not a valid index for a JSON array" % path)
try:
Expand All @@ -415,7 +439,7 @@ def add(self, path, value, obj, **discard):
raise PathError("specified index '%s' cannot be greater than the number of elements in JSON array" % path)
else:
raise PathError("could not find index '%s' in JSON array" % path)
obj[int(path)], chg, tst = self.add(remaining, value, next_obj)
obj[int(path)], chg, tst = self.add(remaining, value, next_obj, create_parents)
return obj, chg, None

# https://tools.ietf.org/html/rfc6902#section-4.2
Expand Down Expand Up @@ -469,7 +493,7 @@ def replace(self, path, value, obj, **discard):
if old_value is None: # the target location must exist for operation to be successful
raise PathError("could not find '%s' member in JSON object" % path)
new_obj, dummy, _ = self.remove(path, obj)
new_obj, chg, tst = self.add(path, value, new_obj)
new_obj, chg, tst = self.add(path, value, new_obj, False)
return new_obj, chg, None

# https://tools.ietf.org/html/rfc6902#section-4.4
Expand All @@ -478,7 +502,7 @@ def move(self, from_path, path, obj, **discard):
chg = False
new_obj, removed, _ = self.remove(from_path, obj)
if removed is not None: # don't inadvertently add 'None' as a value somewhere
new_obj, chg, tst = self.add(path, removed, new_obj)
new_obj, chg, tst = self.add(path, removed, new_obj, False)
return new_obj, chg, None

# https://tools.ietf.org/html/rfc6902#section-4.5
Expand All @@ -487,7 +511,7 @@ def copy(self, from_path, path, obj, **discard):
value = self._get(from_path, obj)
if value is None:
raise PathError("could not find '%s' member in JSON object" % path)
new_obj, chg, _ = self.add(path, value, obj)
new_obj, chg, _ = self.add(path, value, obj, False)
return new_obj, chg, None

# https://tools.ietf.org/html/rfc6902#section-4.6
Expand Down
Loading