Skip to content
Luke Deen Taylor edited this page Jun 19, 2016 · 5 revisions

Examples

Note: see Installing for basic setup instructions.

Basic usage

livejson is intentionally easy to use. Using livejson in its most basic form doesn't require much new knowledge, just use the same interface you're familiar with from lists and dicts.

Initialization

To initialize a new file, just call livejson.File.

import livejson
foo = livejson.File("test.json")

Now we have a new file, called test.json. It's as empty as JSON files get, it just contains {}.

You can open existing JSON files in exactly the same way, their contents will be preserved.

Reading and writing

To read from and write to a livejson.File, just pretend it's a dict.

So, to write:

foo["key"] = "value"

and to read it back:

bar = foo["key"]

Performant operations

livejson can be really slow sometimes. This comes as a consequence of its "live" nature; every single access to the database or change to a value involves opening, reading or writing, and closing the file. This works great for small files, but it can be an issue on larger files. Fortunately, livejson implements caching for just this purpose.

You can use livejson with a short-term cache if you know you're going to be doing a lot all at once. Caching is as simple as wrapping whatever operations you want to do in a with block:

foo = livejson.ListFile("test.json")
with foo:
    for i in range(10000):
        foo.append(i)

In this way, you can perform many operations very quickly. See Performance for more details.

Array-based JSON files

JSON files can be just an array. This means a JSON file can start with [, like this:

["a", "b", "c", {"a": "b"}]

livejson fully supports this type of file. If you've already got this kind of file, using

livejson.File("my_array_file.json")

will automatically create an object that behaves like a list.

To initialize a new file of this type, use

foo = livejson.ListDatabase("test.json")