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

Could set_pointer create structures if it can't find any? #41

Open
odscjames opened this issue May 13, 2020 · 2 comments
Open

Could set_pointer create structures if it can't find any? #41

odscjames opened this issue May 13, 2020 · 2 comments

Comments

@odscjames
Copy link

>>> data = {}
>>> set_pointer(data, "/cat/name", "whiskers")
Traceback (most recent call last):
  File "......./jsonpointer.py", line 276, in walk
    return doc[part]
KeyError: 'cat'

During handling of the above exception, another exception occurred:

..........
    raise JsonPointerException("member '%s' not found in %s" % (part, doc))
jsonpointer.JsonPointerException: member 'cat' not found in {}

Could there be an option (off by default) to create dicts/lists as it tries to set things? So instead you'd get:

>>> data = {}
>>> set_pointer(data, "/cat/name", "whiskers", option=True)
{'cat': {'name': 'whiskers'}}

I started hacking on something at https://github.com/stefankoegl/python-json-pointer/compare/master...odscjames:set-create-structures?expand=1

More needs to be done on that, but if I can get something to work is this something your interested in?

I can see there might always be some edge cases around things like creating lists, and I don't think that could be fixed but it might still be useful?

@SquareByte
Copy link

NB: The spec would allow that, but it is not required

For example, some applications might stop pointer processing upon an error, while others may attempt to recover from missing values by inserting default ones.

@alb3rtom
Copy link

alb3rtom commented Nov 10, 2022

>>> from jsonpointer import set_pointer
>>> obj = {'cities': {}}
>>> set_pointer(obj, '/cities/NewYork', '0')
>>> print(obj)
'cities': {'NewYork': '0'}}

>>> set_pointer(obj, '/cities/LosAngeles/population', '4mln')
>>> print(obj)
---------------------------------------------------------------------------
KeyError: 'LosAngeles'
...
JsonPointerException("member '%s' not found in %s" % (part, doc))
JsonPointerException: member 'LosAngeles' not found in {'NewYork': '0'}

@odscjames, currently it is possible to set a single missing level works, but it is not possible to go deeper. I think it might be useful to implement this feature recursively.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants