msiemens / tinydb

TinyDB is a lightweight document oriented database optimized for your happiness :)
https://tinydb.readthedocs.org
MIT License
6.75k stars 536 forks source link

Is there a way to set the JSON output to be structured? #126

Closed roesel closed 7 years ago

roesel commented 7 years ago

I like TinyDB, it does its job well and is less painful than plain text files. However, when looking into the output JSON file, I see one long line of never-ending text.

Is there a flag to set in order to have the output structured, perhaps to a certain depth?

To give an example, I currently store data in the form

{"table":{"1":{"date":"2017-02-06 10:33:43","humidity":53.23,"stamp":1486373623418,"temperature":21.97},"2":{"date":"2017-02-06 10:33:45","humidity":53.23,"stamp":1486373625422,"temperature":21.97},"3":{"date":"2017-02-06 10:33:47","humidity":53.02,"stamp":1486373627428,"temperature":21.98},"4":{"date":"2017-02-06 10:33:49","humidity":53.02,"stamp":1486373629433,"temperature":21.98},"5":{"date":"2017-02-06 11:07:40","humidity":53.27,"stamp":1486375660853,"temperature":22.22}}}

and what I would like to achieve is this

{"table": {
    "1":{"date":"2017-02-06 10:33:43","humidity":53.23,"stamp":1486373623418,"temperature":21.97},
    "2":{"date":"2017-02-06 10:33:45","humidity":53.23,"stamp":1486373625422,"temperature":21.97},
    "3":{"date":"2017-02-06 10:33:47","humidity":53.02,"stamp":1486373627428,"temperature":21.98},
    "4":{"date":"2017-02-06 10:33:49","humidity":53.02,"stamp":1486373629433,"temperature":21.98},
    "5":{"date":"2017-02-06 11:07:40","humidity":53.27,"stamp":1486375660853,"temperature":22.22}
}}

or at least something along those lines (fully structured would work as well, although setting the depth would be awesome).

I looked in the docs, but couldn't find a solution. Any ideas would be appreciated.

msiemens commented 7 years ago

There's a little-known feature with the JSONStorage where you can pass additional arguments to the TinyDB constructor which are passed through to the json.dump() method (see the note in this section of the docs). Long story short, you could use something like this:

db = TinyDB('db.json', sort_keys=True, indent=4, separators=(',', ': '))
db.insert({'b': 1})
db.insert({'a': 1})

That would result in a file like this:

{
    "_default": {
        "1": {
            "b": 1
        },
        "2": {
            "a": 1
        }
    }
}
roesel commented 7 years ago

Thank you, this pretty much works for me. I'll look into the JSONStorage module if there is any way to specify the depth at which structuring should stop. But I realize this is a pretty strange requirement.

Cheers 👍