Search code examples
pythonpython-3.xtinydb

Python tinydb - How to get specific element name?


This is what my structure looks like:

{'MovieName': 'Its-a-Wonderful-Life', 'Description': 'MovieDiscription', 'IMDBID': '0038650'}

I want to print out only the MovieName element.

I'm using this code to get it:

db = TinyDB('Databases/Downloaded_Movies.json')

for item in db:

   print(item.MovieName)

but I'm getting this error:

 AttributeError: 'Document' object has no attribute 'MovieName'

How do I fix the code?


Solution

  • TinyDB expects an indexed table document, not a list. Unless you want to write a custom middleware for your TinyDB, you'll either have to modify your JSON

    "1 ": {'MovieName': 'Its-a-Wonderful-Life', 'Description': 'MovieDiscription', 'IMDBID': '0038650'}
    

    or you can try to print the element with indexes as

    import json
    wjson = db.read()    
    wjdata = json.loads(wjson)
    print wjdata['1'][0]['Moviename']