jsonfile/README.md

1.9 KiB
Executable File

jsonfile

version 0.9

The jsonfile Python module can be used to sync a JSON file on a disk with the corresponding Python object instance.

Can be used to autosave JSON compatible Python data.

By default the content of the JSON file is human readable and version control friendly.

WARNING! This results an extremely slow backend!

>>> import jsonfile
>>> j = jsonfile.jsonfile("j.json")
>>> j.data
Ellipsis
>>> # Ellipsis indicates no data
>>> j.data = ["Hello"]
>>> # `jsonfile` files are not autosaved anymore by default
>>> j.save() # this will do it though
>>> # I recommend using a context manager to save transactions:
>>> with j as d:  # d now refers to j.data
...     d.append("World")
...     d.insert(1, "Beautiful")
...
>>> # Now the changes are saved to disk at the end
>>> with j:
...     del d[1]
...
>>> del j
>>> # `j.json` has not been deleted; that would require an explicit j.delete()
>>> j
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'j' is not defined
>>> j = jsonfile.jsonfile("j.json") # let's reload it
>>> j.data
['Hello', 'World']
>>> o = j.data.copy()
>>> o
['Hello', 'World']
>>> # this is a native Python representation of the internal data;
>>> # changes made on it will not effect the content of the file
>>> type(o)
<class 'list'>
>>> with j as d:
...     j.data = {"original": d, "new": "Hello Brave New World!"}
...
>>> print(j.datastring())
{
        "new": "Hello Brave New World!",
        "original": [
                "Hello",
                "World"
        ]
}
>>> j.delete() # `j.json` file gets deleted
>>> with j as d:
...     d["magical"] = "phoenix"
...     del d["original"]
...
>>> # file has been recreated with new content:
>>> print(j.datastring())
{
        "magical": "phoenix",
        "new": "Hello Brave New World!"
}
>>>