Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i insert multiple tables into a table using TinyDB?

I have been trying to create multiple tables in a table using TinyDB. Here is a website to help you understand what TinyDb is (TinyDB PDF). The PDF file did not show how to insert multiple tables into one, one multiple data into one table.

I intended the json file to look like this:

"MASTER TABLE": 
{
     {"TABLE 1": {"1": {"Name": "Alice", "Age": 19}}
     {"TABLE 2": {"1": {"Name": "John", "Age": 12}}, 
}

However, the issue is that I'm not sure how to insert Table1 and Table2 into the Master file table. SO it gave me the error that table1 is not an element. I know it isn't an element but I don't have any idea of how to fix it, to put the two tables under the Master file table. I'd appreciate any help.

Here's my codes:

from tinydb import TinyDB, Query
from tinydb import TinyDB, where
import json

with open("/home/pi/Desktop/jsontest/test.json", 'w+'):
    table1 = TinyDB('/home/pi/Desktop/jsontest/test.json')
    table1 = table1.table('TABLE 1')
    table1.insert_multiple([{'Name' : 'Alice' , 'Age' : 19}])

    table2 = TinyDB('/home/pi/Desktop/jsontest/test.json')
    table2 = table2.table('TABLE 2')
    table2.insert_multiple([{'Name' : 'john' , 'Age' : 12}])

    overall = TinyDB('/home/pi/Desktop/jsontest/test.json')
    overall = overall.table('MASTER TABLE')
    overall.insert([table1])
like image 498
meh Avatar asked Feb 06 '26 03:02

meh


1 Answers

It doesn't make sense to insert tables into another table ?

from tinydb import TinyDB

db = TinyDB('db.json')

table1 = db.table('TABLE 1')
table1.insert({'Name' : 'Alice' , 'Age' : 19})

table2 = db.table('TABLE 2')
table2.insert({'Name' : 'john' , 'Age' : 12})

Gives db.json containing:

{
   "_default": {}, 
   "TABLE 1": {"1": {"Name": "Alice", "Age": 19}}, 
   "TABLE 2": {"1": {"Name": "john", "Age": 12}}
}

I think your JSON is incorrect, you cannot the syntax (key, value) here:

"MASTER TABLE": 
{
    {"TABLE 1": {"1": {"Name": "Alice", "Age": 19}}
    {"TABLE 2": {"1": {"Name": "John", "Age": 12}}, 
}

You can do that:

from tinydb import TinyDB

db = TinyDB('db.json', default_table='MASTER TABLE')

master_table = db.table('MASTER TABLE')
master_table.insert({"TABLE 1": {"1": {"Name": "Alice", "Age": 19}}})
master_table.insert({"TABLE 2": {"1": {"Name": "John", "Age": 12}}})

You obtain db.json containing:

{
  "MASTER TABLE": {
      "1": {"TABLE 1": {"1": {"Name": "Alice", "Age": 19}}}, 
      "2": {"TABLE 2": {"1": {"Name": "John", "Age": 12}}}
  }
}

But it is strange.

like image 103
glegoux Avatar answered Feb 07 '26 21:02

glegoux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!