Python TinyDB

Page content

Storing Data in JSON - TinyDB

Small Example how to Store Data in JSON, and Query them afterwards like a NOSQL DB. Have a look at TinyDB if you wanna see more.

Code

from tinydb import TinyDB, Query
from pprint import pprint

# Create or load a database file
db = TinyDB('db.json')

# insert some sample data
def insert():
    # Insert data
    db.insert({'name': 'John', 'age': 30})
    db.insert({'name': 'Alice', 'age': 25, 'hobbies': 'sleep'})
    db.insert({'name': 'Max', 'age': 20, 'hobbies': ['sleep', 'play', 'eat']})

# show all entries
def show_all():
    all_records = db.all()
    pprint(all_records)

# entries with hobbies
def show_entries_with_hobbies():
    User = Query()
    result = db.search(User.hobbies.exists())
    pprint(result)

# entries without hobbies
def show_entries_without_hobbies():
    User = Query()
    result = db.search(~User.hobbies.exists())
    pprint(result)

# show entries with hobbies and older than 22 years
def show_entries_with_hobbies_and_older_than_22():
    User = Query()
    result =  db.search((User.hobbies.exists()) & (User.age > 22))
    pprint(result)

if __name__ == "__main__":
  # Add
  insert()

  # show
  print("\n-- ALL --")
  show_all()

  print("\n-- with Hobbies --")
  show_entries_with_hobbies()

  print("\n-- without Hobbies --")
  show_entries_without_hobbies()


  print("\n-- with Hobbies and older than 22 --")
  show_entries_with_hobbies_and_older_than_22()

Run

you need to install tinydb. use a virtual env like .venv, poetry or whatever you like

python main.py 

-- ALL --
[{'age': 30, 'name': 'John'},
 {'age': 25, 'hobbies': 'sleep', 'name': 'Alice'},
 {'age': 20, 'hobbies': ['sleep', 'play', 'eat'], 'name': 'Max'}]

-- with Hobbies --
[{'age': 25, 'hobbies': 'sleep', 'name': 'Alice'},
 {'age': 20, 'hobbies': ['sleep', 'play', 'eat'], 'name': 'Max'}]

-- without Hobbies --
[{'age': 30, 'name': 'John'}]

-- with Hobbies and older than 22 --
[{'age': 25, 'hobbies': 'sleep', 'name': 'Alice'}]

Any Comments ?

sha256: 8bde90a45c81121ced47c61cf4eb1227a44511e003614684072cf714fa27a164