Python jsonpatch.JsonPatch() Examples

The following are code examples for showing how to use jsonpatch.JsonPatch(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: appr   Author: app-registry   File: kub.py    Apache License 2.0 6 votes vote down vote up
def _apply_patches(self, resources):
        for _, resource in resources.iteritems():
            if self.namespace:
                if 'namespace' in resource['value']['metadata']:
                    op = 'replace'
                else:
                    op = 'add'
                resource['patch'].append({
                    "op": op,
                    "path": "/metadata/namespace",
                    "value": self.namespace})

            if len(resource['patch']):
                patch = jsonpatch.JsonPatch(resource['patch'])
                result = patch.apply(resource['value'])
                resource['value'] = result
        return resources 
Example 2
Project: pyhf   Author: scikit-hep   File: workspace.py    Apache License 2.0 6 votes vote down vote up
def model(self, **config_kwargs):
        """
        Create a model object with/without patches applied.

        Args:
            patches: A list of JSON patches to apply to the model specification

        Returns:
            ~pyhf.pdf.Model: A model object adhering to the schema model.json
        """
        measurement = self.get_measurement(**config_kwargs)
        log.debug(
            'model being created for measurement {0:s}'.format(measurement['name'])
        )

        patches = config_kwargs.get('patches', [])

        modelspec = {
            'channels': self['channels'],
            'parameters': measurement['config']['parameters'],
        }
        for patch in patches:
            modelspec = jsonpatch.JsonPatch(patch).apply(modelspec)

        return Model(modelspec, poiname=measurement['config']['poi'], **config_kwargs) 
Example 3
Project: ludobox   Author: ludobox   File: utils.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def json_serial(obj):
    """JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, datetime):
        serial = obj.isoformat()
        return serial
    elif isinstance(obj, JsonPatch):
        serial = list(obj)
        return serial
    # raise TypeError ("Type not serializable") 
Example 4
Project: ludobox   Author: ludobox   File: history.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def apply_update_patch(content, event):
    """Apply JSON diff patches to content"""
    patch = JsonPatch(event["content"]["changes"])
    final_content = patch.apply(content)
    return final_content 
Example 5
Project: pyhf   Author: scikit-hep   File: rootio.py    Apache License 2.0 5 votes vote down vote up
def json2xml(workspace, output_dir, specroot, dataroot, resultprefix, patch):
    try:
        import uproot

        assert uproot
    except ImportError:
        log.error(
            "json2xml requires uproot, please install pyhf using the "
            "xmlio extra: pip install pyhf[xmlio]"
        )
    from .. import writexml

    ensure_dirs(output_dir)
    with click.open_file(workspace, 'r') as specstream:
        spec = json.load(specstream)
        for pfile in patch:
            patch = json.loads(click.open_file(pfile, 'r').read())
            spec = jsonpatch.JsonPatch(patch).apply(spec)
        ensure_dirs(os.path.join(output_dir, specroot))
        ensure_dirs(os.path.join(output_dir, dataroot))
        with click.open_file(
            os.path.join(output_dir, '{0:s}.xml'.format(resultprefix)), 'w'
        ) as outstream:
            outstream.write(
                writexml.writexml(
                    spec,
                    os.path.join(output_dir, specroot),
                    os.path.join(output_dir, dataroot),
                    resultprefix,
                ).decode('utf-8')
            ) 
Example 6
Project: watcher   Author: openstack   File: utils.py    Apache License 2.0 5 votes vote down vote up
def apply_jsonpatch(doc, patch):
    for p in patch:
        if p['op'] == 'add' and p['path'].count('/') == 1:
            if p['path'].lstrip('/') not in doc:
                msg = _('Adding a new attribute (%s) to the root of '
                        ' the resource is not allowed')
                raise wsme.exc.ClientSideError(msg % p['path'])
    return jsonpatch.apply_patch(doc, jsonpatch.JsonPatch(patch)) 
Example 7
Project: iotronic   Author: MDSLab   File: utils.py    Apache License 2.0 5 votes vote down vote up
def apply_jsonpatch(doc, patch):
    for p in patch:
        if p['op'] == 'add' and p['path'].count('/') == 1:
            if p['path'].lstrip('/') not in doc:
                msg = _('Adding a new attribute (%s) to the root of '
                        ' the resource is not allowed')
                raise wsme.exc.ClientSideError(msg % p['path'])
    return jsonpatch.apply_patch(doc, jsonpatch.JsonPatch(patch)) 
Example 8
Project: openstack-iot   Author: digambar15   File: utils.py    Apache License 2.0 5 votes vote down vote up
def apply_jsonpatch(doc, patch):
    for p in patch:
        if p['op'] == 'add' and p['path'].count('/') == 1:
            if p['path'].lstrip('/') not in doc:
                msg = _('Adding a new attribute (%s) to the root of '
                        ' the resource is not allowed')
                raise wsme.exc.ClientSideError(msg % p['path'])
    return jsonpatch.apply_patch(doc, jsonpatch.JsonPatch(patch))