@liuguiyu, the below shows how to take a json file and write it out to tinydb. A little more code, as I write out a valid json file as you may have on disk and read it back in so its complete example. Also some error checking around the import statements. Also using Fake to create some creditable data.
Maybe this is very straight fwd to you, if so just ignore.
try:
from tinydb import TinyDB, Query, __version__ as tinydb_version
except ImportError:
print('tinydb v3.4.1 or greater needs to be insalled to run this application')
exit(1)
try:
from faker import Faker
except ImportError:
print('faker to be insalled to run this application')
exit(1)
fake = Faker()
fake.seed(2017) # the seed keeps the results the same
import json
_json_file = 'junk.json'
_tiny_db_file = 'conversion_tdb.json'
def create_json_file(file_name, num_recs=50):
'''
func to create simple json file
'''
recs = [{'idx':i, 'first':fake.first_name(),
'last':fake.last_name()} for i in range(num_recs)]
with open(file_name, 'w') as fp:
json.dump(recs, fp)
# create a json file, as you may have it stored on disk already
create_json_file(_json_file)
# now open and read the json file
with open(_json_file) as fp:
json_records_from_file = json.load(fp)
print('Number JSON records read in... = ', len(json_records_from_file))
tdb = TinyDB(_tiny_db_file) # open/create a tinydb file
tdb.purge_table('_default') # delete the records inthe default table
# write the json records to the tinydb database. Using insert_multiple
# method as we have a list of dicts. We are writing the records as they have
# been read in. But of course we could do modifications first if we wanted to.
tdb.insert_multiple(json_records_from_file)
tdb.close() # close the tinydb file
# Now re-open the existing tinydb file, and iterate over the tdb obj
# printing each element and its eid...
tdb = TinyDB(_tiny_db_file)
for elm in tdb:
print(elm , 'element id:',elm.eid)
tdb.close()