from itertools import groupby
import json
from operator import itemgetter
import mysql.connector
cnx = mysql.connector.connect(
database='somedb', user='root', password='root', host='localhost'
)
cursor = cnx.cursor()
data = {}
cursor.execute("""
SELECT item.recipe_id
, meta.meta_value AS instruction_text
FROM wp_simmer_recipe_items item
INNER JOIN wp_simmer_recipe_itemmeta meta
ON item.recipe_item_id = meta.recipe_item_id
WHERE
item.recipe_item_type = 'instruction'
AND meta.meta_key <> 'is_heading'
ORDER BY item.recipe_id, item.recipe_item_order
""")
for recipe_id, instructions in groupby(cursor.fetchall(), itemgetter(0)):
data[recipe_id] = {
'instructions': [row[1] for row in instructions],
'ingredients': [],
}
cursor.execute("""
SELECT item.recipe_id
, meta.recipe_item_id
, meta.meta_key
, meta.meta_value
FROM wp_simmer_recipe_items item
INNER JOIN wp_simmer_recipe_itemmeta meta
ON item.recipe_item_id = meta.recipe_item_id
WHERE
item.recipe_item_type <> 'instruction'
ORDER BY item.recipe_id, item.recipe_item_order, meta.meta_key
""")
for (recipe_id, _), item in groupby(cursor.fetchall(), itemgetter(0, 1)):
data[recipe_id]['ingredients'] = [
.append({row[2]: row[3] for row in item_attributes}
for _, item_attributes in groupby(item, itemgetter(0, 1)})
]
cursor.close()
cnx.close()
with open('data.json', 'w') as outfile:
json.dump(data, outfile, sort_keys=True, indent=4)