stefankoegl / python-json-pointer

Resolve JSON Pointers in Python
https://python-json-pointer.readthedocs.org/
Other
141 stars 43 forks source link

support setting values by pointer #1

Closed peritus closed 13 years ago

peritus commented 13 years ago

I'd like to be able to set values at the specified pointer using this library.

Pseudo-Code:

>>> obj = {"foo":  2}
>>> pointer = JsonPointer(obj, "/bar")
>>> pointer.set("baz", 3)
>>> obj
{"foo":  2, "baz": 3}

node-jsonpointer supports this: https://github.com/janl/node-jsonpointer#readme

stefankoegl commented 13 years ago

I'm not quite sure why you specified the "/bar" in the second line of your example, but it made me think about an extended use of your suggestion.

You could specify like a base path in the JsonPointer instance, and provide a relative path in the set method. Then you could use it like

>>> obj = {"foo": 2}
>>> pointer = JsonPointer(obj, "/bar")

# provide a relative path in the call to set
>>> pointer.set("x", 3)
>>> pointer.set("y", 4)
>>> obj
{"foo": 2, "bar": {"x": 3, "y": 4}}

# if no relative path is given, set the path from the constructor
>>> pointer.set(10)
>>> obj
{"foo": 2, "bar": 10}

What do you think about this interface?

peritus commented 13 years ago

Right, metasyntactical confusion ;) It should read

>>> pointer = JsonPointer(obj, "/")

I like your interface with the optional second parameter.

Also worth considering:

>>> obj = {"foo": 2}
>>> pointer = JsonPointer(obj, "/bar")
>>> pointer.set(0, "one")
>>> pointer.set(1, "two")
>>> obj
{"foo": 2, "bar": ["one", "two"]}

and

>>> obj = {"foo": 2}
>>> pointer = JsonPointer(obj, "/bar")
>>> pointer.set(["three", "four"])
>>> obj
{"foo": 2, "bar": ["three", "four"]}

so long, Filip

stefankoegl commented 13 years ago

I have to correct my original proposal once again, because the object isn't passed to the JsonPointer directly, because it should be possible to apply one pointer to several objects.

Therefor I'd go for an interface like

>>> obj = {"foo": 2}
>>> pointer = JsonPointer("/bar")
>>> pointer.set(obj, "test", 2)
>>> obj
{"foo": 2, "bar": {"test": 2}}
peritus commented 13 years ago

Right. Also correct my API draft in this regard.

Aside: Can JsonPointer.get be an alias for JsonPointer.resolve ?

peritus commented 13 years ago

Thank you very much for implementing this! I owe you a beer!

Could you publish that to PyPI ? I have a little library in the works that I want to depend on your work.

stefankoegl commented 13 years ago

no problem, I've pushed version 0.2 to pypi