Вставка сложного объекта json в схему sql - PullRequest
0 голосов
/ 31 декабря 2018

У меня есть объект json в форме

{   
    "483329": 
    {"Dairy_free": false,
     "Gluten_free": true,
     "Vegetarian": false,
     "Vegan": false, 
     "ketagonic": false},

     "577539": 
     {"Dairy_free": true,
      "Gluten_free": false, 
      "Vegetarian": true, 
      "Vegan": true, 
      "ketagonic": false}
}

Где схема

    | id | Dairy_free | Gluten_free | Vegetarian | Vegan|  ketagonic|
    +----+------------+-------------+------------+------+-----------+


Есть ли способ без повторной генерацииjson для вставки объекта json в mysql, используя mysqlcursors?

sql_insert = INSERT INTO allergies VALUES (Default, %s %s %s %s %s);"
cursor = config.cursor
for obj in json_objects <---- this is where I need to transfer to suitable object
try:
    affected_count = cursor.execute(sql_insert, (object))
    config.dbconnection.commit()
except Exception as e:
    print e

1 Ответ

0 голосов
/ 31 декабря 2018

Может использоваться executemany, за которым следует Руководство пользователя MySQLdb

data = list(map(lambda x: tuple(x.values()), json_objects.values()))
# [(False, True, False, False, False), (True, False, True, True, False)]

c.executemany(
    """INSERT INTO allergies VALUES (Default, %s, %s, %s, %s, %s)""",
    data
)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...