создай скрипт на питоне, который будет брать меню по ссылке:…
- User
создай скрипт на питоне, который будет брать меню по ссылке: https://dodopizza.by/api/v5/menu?languageCode=ru-RU&countryCode=112&menuType=Delivery&locationId=000D3A262427A94A11E8A639F069F9E1 и оставлять только пиццы, сохранять в новый файл json
- Assistant
Конечно! Вы можете использовать библиотеки
requestsиjsonв Python для получения данных и фильтрации меню. Вот пример скрипта, который делает это:import requests import json def fetch_menu(url): response = requests.get(url) if response.status_code == 200: return response.json() else: raise Exception(f"Failed to fetch data: {response.status_code}") def filter_pizzas(menu_data): pizzas = [item for item in menu_data['products'] if item['type'] == 'Pizza'] return pizzas def save_to_json(data, filename): with open(filename, 'w', encoding='utf-8') as file: json.dump(data, file, ensure_ascii=False, indent=4) def main(): url = "https://dodopizza.by/api/v5/menu?languageCode=ru-RU&countryCode=112&menuType=Delivery&locationId=000D3A262427A94A11E8A639F069F9E1" menu_data = fetch_menu(url) pizzas = filter_pizzas(menu_data) save_to_json(pizzas, 'filtered_pizzas.json') print("Filtered pizzas have been saved to filtered_pizzas.json") if __name__ == "__main__": main()Описание скрипта:
-
Функция
fetch_menu(url): Выполняет HTTP GET запрос к указанному URL и возвращает JSON данные, если запрос успешен. -
Функция
filter_pizzas(menu_data): Принимает на вход полные данные меню и фильтрует только те элементы, которые имеют типPizza. -
Функция
save_to_json(data, filename): Сохраняет отфильтрованные данные в новый JSON файл с указанным именем. -
Функция
main(): Собирает все вместе. Вызывает функции для получения меню, фильтрации и сохранения результатов. Выводит сообщение, когда процесс завершен.
Использование:
- Убедитесь, что у вас установлены библиотеки
requests(если нет, выполнитеpip install requests). - Запустите скрипт. Он создаст файл
filtered_pizzas.json, содержащий только пиццы.
Этот скрипт предназначен для работы с данной конкретной структурой меню. Убедитесь, что URL и данные меню соответствуют ожидаемой структуре.
-
- User
переделай чтобы скрипт брал файл локально
- Assistant
Конечно! Если вы хотите работать с локальным файлом, содержащим данные меню в формате JSON, все что вам нужно сделать, это заменить часть кода, которая загружает данные из сети, на часть, которая загружает данные из файла. Я покажу, как это сделать:
import json def load_menu_from_file(filename): with open(filename, 'r', encoding='utf-8') as file: return json.load(file) def filter_pizzas(menu_data): pizzas = [item for item in menu_data['products'] if item['type'] == 'Pizza'] return pizzas def save_to_json(data, filename): with open(filename, 'w', encoding='utf-8') as file: json.dump(data, file, ensure_ascii=False, indent=4) def main(): input_filename = 'local_menu.json' # Укажите здесь имя вашего файла с меню output_filename = 'filtered_pizzas.json' menu_data = load_menu_from_file(input_filename) pizzas = filter_pizzas(menu_data) save_to_json(pizzas, output_filename) print(f"Filtered pizzas have been saved to {output_filename}") if __name__ == "__main__": main()Описание изменений:
-
Функция
load_menu_from_file(filename): Открывает указанный локальный файл и загружает данные JSON. Убедитесь, что файл называетсяlocal_menu.json, или измените имя файла в коде на подходящее. -
Функция
main(): Определяет входной и выходной файлы и использует новую функцию для загрузки данных из локального файла.
Использование:
- Поместите ваш JSON файл с полным меню рядом со скриптом и назовите его
local_menu.jsonили изменитеinput_filenameна имя вашего файла. - Запустите скрипт, и он создаст файл
filtered_pizzas.json, содержащий только пиццы.
-
- User
Traceback (most recent call last): File "C:\Users\CARMANBY\Downloads\dodo_pizza_scraper.py", line 25, in main() File "C:\Users\CARMANBY\Downloads\dodo_pizza_scraper.py", line 20, in main pizzas = filter_pizzas(menu_data) ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\CARMANBY\Downloads\dodo_pizza_scraper.py", line 8, in filter_pizzas pizzas = [item for item in menu_data['products'] if item['type'] == 'Pizza'] ~~~~~~~~~^^^^^^^^^^^^ KeyError: 'products'
- Assistant
Ошибка
KeyError: 'products'указывает на то, что в вашем JSON-файле нет ключа'products'. Это может быть вызвано несколькими факторами:-
Неправильная структура JSON: Возможно, структура JSON-файла отличается от ожидаемой. Нужно убедиться, что JSON-файл содержит ключ
'products', который должен иметь список продуктов. -
Ошибка в формате данных: Возможно, JSON-файл повреждён или имеет неверный формат.
Чтобы решить эту проблему, вы можете предпринять следующие шаги:
Диагностика и Решение
-
Проверьте структуру JSON-файла:
- Откройте файл
local_menu.jsonв текстовом редакторе или JSON-редакторе. - Убедитесь, что он содержит правильную структуру и наличие ключа
'products'.
- Откройте файл
-
Использование отладочного вывода:
- Добавьте вывод содержимого JSON-файла перед фильтрацией, чтобы увидеть, какие данные вы загружаете:
def main(): input_filename = 'local_menu.json' output_filename = 'filtered_pizzas.json' menu_data = load_menu_from_file(input_filename) print(json.dumps(menu_data, indent=4, ensure_ascii=False)) # Вывод данных для проверки pizzas = filter_pizzas(menu_data) save_to_json(pizzas, output_filename) print(f"Filtered pizzas have been saved to {output_filename}") -
Адаптация к различным структурам:
- Если структура отличается, адаптируйте код фильтрации под фактическую структуру JSON.
Например, если ваши данные приходят в другой структуре, измените фильтр так, чтобы он соответствовал действительности:
def filter_pizzas(menu_data): # Пример для альтернативной структуры данных # Предположим, продукты находятся по ключу 'items' pizzas = [item for item in menu_data['items'] if item['category'] == 'Pizza'] return pizzas- Проверка синтаксиса и целостности JSON:
- Если файл поврежден, попробуйте исправить или заново его сохранить в корректном формате.
Эти шаги помогут вам диагностировать и устранить проблему с загрузкой и фильтрацией данных.
-
- User
данные выводятся, и их много
- Assistant
Если данные выводятся и JSON-файл содержит много информации, но структура отличается от ожидаемой (нет ключа
'products'), необходимо адаптировать код для работы с фактической структурой данных.Как подойти к решению:
-
Изучите структуру:
- Поищите ключи на верхнем уровне структуры JSON и определите ключи, которые ведут к нужным данным (например, к списку продуктов или пицц).
-
Найдите элемент, который соответствует продуктам:
- Обратите внимание на ключи, которые могут содержать список продуктов. Они могут быть названы иначе, чем
'products'.
- Обратите внимание на ключи, которые могут содержать список продуктов. Они могут быть названы иначе, чем
-
Адаптируйте код фильтрации:
- Если продукты находятся под другим ключом, измените код, чтобы использовать правильный ключ.
Пример кода на основе возможной альтернативной структуры:
Предположим, что ключ, содержащий список продуктов, называется
'items', а внутри каждого продукта есть нужная информация.import json def load_menu_from_file(filename): with open(filename, 'r', encoding='utf-8') as file: return json.load(file) def filter_pizzas(menu_data): # Измените 'items' и условия фильтрации согласно фактической структуре данных. if 'items' in menu_data: pizzas = [item for item in menu_data['items'] if item.get('category') == 'Pizza'] else: print("Ключ 'items' не найден в JSON-данных.") pizzas = [] return pizzas def save_to_json(data, filename): with open(filename, 'w', encoding='utf-8') as file: json.dump(data, file, ensure_ascii=False, indent=4) def main(): input_filename = 'local_menu.json' # Укажите здесь имя вашего файла с меню output_filename = 'filtered_pizzas.json' menu_data = load_menu_from_file(input_filename) print(json.dumps(menu_data, indent=4, ensure_ascii=False)) # Вывод данных для проверки pizzas = filter_pizzas(menu_data) save_to_json(pizzas, output_filename) print(f"Filtered pizzas have been saved to {output_filename}") if __name__ == "__main__": main()Что делать, если структура сложнее:
-
Используйте отладочный вывод. Найдите ключи внутри JSON, которые приводят к продуктам. Внимательно изучите вложенные структуры.
-
Измените условия фильтрации, чтобы они соответствовали правильным параметрам, если у продуктов нет прямого указания на их категорию как 'Pizza'.
-
При необходимости улучшите логику. Если ваш JSON более сложен, может понадобиться пройти по нескольким уровням вложенности до нужных данных.
Эти инструкции помогут вам адаптировать скрипт для работы с вашим конкретным набором данных. Если структура сильно отличается, пожалуйста, уточните, и я постараюсь более точно помочь.
-
- User
часть кода:
{ "$id": "#/items/137/variations/44/product/ingredientGroups/1", "code": "fgsh", "isBasis": false, "name": "моцарелла", "choiceType": "None", "totalQuantityMin": 1, "totalQuantityMax": 1, "ingredients": [ { "$id": "#/items/137/variations/44/product/ingredientGroups/1/ingredients/0", "materialTypeId": "000d3a27d5a4a94411e87ab2dd132cf3", "name": "Моцарелла", "quantity": 1, "quantityVariations": [ { "$id": "#/items/137/variations/44/product/ingredientGroups/1/ingredients/0/quantityVariations/0", "name": "", "quantity": 1, "price": 0, "translations": { "$id": "#/items/137/variations/44/product/ingredientGroups/1/ingredients/0/quantityVariations/0/translations" } } ], "index": 0, "imageLink": "https://cdn.dodostatic.net/static/Img/Ingredients/74c62256e82a4a78a646251490446369.png", "mediaServiceImageId": "11ee7f0ceaae1cc98754590de178c0f7", "translations": { "$id": "#/items/137/variations/44/product/ingredientGroups/1/ingredients/0/translations", "Name": { "$ref": "#/items/0/variations/0/product/ingredientGroups/2/ingredients/0/translations/Name" } } } ], "index": 3, "additionalData": [], "translations": { "$id": "#/items/137/variations/44/product/ingredientGroups/1/translations", "Name": { "$ref": "#/items/137/variations/14/product/ingredientGroups/1/translations/Name" } } }, { "$id": "#/items/137/variations/44/product/ingredientGroups/2", "code": "aohb", "isBasis": false, "name": "соус альфредо", "choiceType": "None", "totalQuantityMin": 1, "totalQuantityMax": 1, "ingredients": [ { "$id": "#/items/137/variations/44/product/ingredientGroups/2/ingredients/0", "materialTypeId": "11eae78f961d0529457ebf07942d0760", "name": "Соус Альфредо", "quantity": 1, "quantityVariations": [ { "$id": "#/items/137/variations/44/product/ingredientGroups/2/ingredients/0/quantityVariations/0", "name": "", "quantity": 1, "price": 0, "translations": { "$id": "#/items/137/variations/44/product/ingredientGroups/2/ingredients/0/quantityVariations/0/translations" } } ], "index": 0, "imageLink": "", "mediaServiceImageId": null, "translations": { "$id": "#/items/137/variations/44/product/ingredientGroups/2/ingredients/0/translations" } } ], "index": 4, "additionalData": [], "translations": { "$id": "#/items/137/variations/44/product/ingredientGroups/2/translations", "Name": { "$ref": "#/items/137/variations/14/product/ingredientGroups/2/translations/Name" } } }, { "$ref": "#/items/137/variations/30/product/ingredientGroups/4" } ], "packageGroups": [ { "$ref": "#/items/137/variations/30/product/packageGroups/0" }, { "$ref": "#/items/137/variations/30/product/packageGroups/1" } ], "images": [ { "$id": "#/items/137/variations/44/product/images/0", "id": "Img/Products/aecb074914d14fbf8217922d1a95af70", "mediaServiceImageId": "11EE7D5EF691E45995BAFD598C8FC4E4", "tags": [ "main" ], "supportedFeatures": { "$id": "#/items/137/variations/44/product/images/0/supportedFeatures", "formats": [ "WebP", "Jpeg", "Png", "Heic" ], "sizes": [ "Size_1875x1875", "Size_760x760", "Size_584x584", "Size_366x366", "Size_292x292", "Size_233x233", "Size_183x183", "Size_146x146", "Size_138x138" ] } } ], "description": "Цыпленок, моцарелла, фирменный соус альфредо", "compositionDescription": "Тесто (мука в/с, вода, масло подсолнечное, сахар, соль, дрожжи), цыпленок, моцарелла, соус альфредо", "expiryPeriod": null, "traits": { "$id": "#/items/137/variations/44/product/traits", "spicy": false, "vegan": false, "forChildren": false, "baked": true, "drink": false, "food": true, "digital": false, "material": false, "hotAndReady": false, "alcohol": false, "pizza": true, "sauce": false }, "allergyAdvice": { "$id": "#/items/137/variations/44/product/allergyAdvice", "contains": "", "mayContain": "глютен, молоко и продукты его переработки (в том числе лактозу), а также некоторые другие аллергены: vdo.do/ru_nutrition", "translations": { "$id": "#/items/137/variations/44/product/allergyAdvice/translations", "MayContain": { "$ref": "#/items/20/variations/0/product/allergyAdvice/translations/MayContain" } } }, "saleTime": null, "additionalData": [ { "$id": "#/items/137/variations/44/product/additionalData/0", "key": "ProductFromHalvesVariationId", "value": "000d3a262427a95011e91ef47bdf9a23" } ], "translations": { "$id": "#/items/137/variations/44/product/translations", "Name": { "$ref": "#/items/20/variations/0/product/translations/Name" }, "Description": { "$ref": "#/items/20/variations/0/product/translations/Description" }, "CompositionDescription": { "$ref": "#/items/20/variations/0/product/translations/CompositionDescription" }, "SizeName": { "$ref": "#/items/0/variations/3/product/translations/SizeName" }, "Size": { "$ref": "#/items/0/variations/3/product/translations/Size" } }, "relatedProducts": [] }, "index": 0, "isDefault": false }, { "$id": "#/items/137/variations/45", "product": { "$id": "#/items/137/variations/45/product", "id": "11ea5a66af9f992d6434be2c13344c60", "metaProductId": "11ea5a65af9f992d6434be2ca8fd22e0", "name": "Деревенская", "size": "35 см", "sizeName": "Большая", "price": 19.59, "foodValue": { "$id": "#/items/137/variations/45/product/foodValue", "proteins": 8.1, "fats": 7.7, "carbohydrates": 27, "calories": 215.7, "weight": null }, "ingredientGroups": [ { "$id": "#/items/137/variations/45/product/ingredientGroups/0", "code": "wshn", "isBasis": false, "name": "картофель из печи", "choiceType": "Single", "totalQuantityMin": 0, "totalQuantityMax": 1, "ingredients": [ { "$id": "#/items/137/variations/45/product/ingredientGroups/0/ingredients/0", "materialTypeId": "000d3a262427a94911e8a4c799e4ad5d", "name": "Картофель соломкой", "quantity": 1, "quantityVariations": [ { "$id": "#/items/137/variations/45/product/ingredientGroups/0/ingredients/0/quantityVariations/0", "name": "", "quantity": 0, "price": 0, "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/0/ingredients/0/quantityVariations/0/translations" } }, { "$id": "#/items/137/variations/45/product/ingredientGroups/0/ingredients/0/quantityVariations/1", "name": "", "quantity": 1, "price": 0, "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/0/ingredients/0/quantityVariations/1/translations" } } ], "index": 0, "imageLink": "", "mediaServiceImageId": null, "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/0/ingredients/0/translations" } } ], "index": 2, "additionalData": [], "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/0/translations", "Name": { "$ref": "#/items/137/variations/15/product/ingredientGroups/0/translations/Name" } } }, { "$id": "#/items/137/variations/45/product/ingredientGroups/1", "code": "pfob", "isBasis": false, "name": "маринованные огурчики", "choiceType": "Single", "totalQuantityMin": 0, "totalQuantityMax": 1, "ingredients": [ { "$id": "#/items/137/variations/45/product/ingredientGroups/1/ingredients/0", "materialTypeId": "000d3a262427a94911e884452320a8b5", "name": "Маринованные огурчики", "quantity": 1, "quantityVariations": [ { "$id": "#/items/137/variations/45/product/ingredientGroups/1/ingredients/0/quantityVariations/0", "name": "", "quantity": 0, "price": 0, "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/1/ingredients/0/quantityVariations/0/translations" } }, { "$id": "#/items/137/variations/45/product/ingredientGroups/1/ingredients/0/quantityVariations/1", "name": "", "quantity": 1, "price": 0, "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/1/ingredients/0/quantityVariations/1/translations" } } ], "index": 0, "imageLink": "https://cdn.dodostatic.net/static/Img/Ingredients/000D3A262427A95111E9EA89CD3AAAFB", "mediaServiceImageId": "11ee7f0cebd147ea81e58ff1946b6c6e", "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/1/ingredients/0/translations", "Name": { "$ref": "#/items/0/variations/0/product/ingredientGroups/7/ingredients/16/translations/Name" } } } ], "index": 3, "additionalData": [], "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/1/translations", "Name": { "$ref": "#/items/137/variations/15/product/ingredientGroups/1/translations/Name" } } }, { "$id": "#/items/137/variations/45/product/ingredientGroups/2", "code": "ypwy", "isBasis": false, "name": "цыпленок", "choiceType": "Single", "totalQuantityMin": 0, "totalQuantityMax": 1, "ingredients": [ { "$id": "#/items/137/variations/45/product/ingredientGroups/2/ingredients/0", "materialTypeId": "000d3a2479f7a94411e87ab35e4ba8d3", "name": "Цыпленок", "quantity": 1, "quantityVariations": [ { "$id": "#/items/137/variations/45/product/ingredientGroups/2/ingredients/0/quantityVariations/0", "name": "", "quantity": 0, "price": 0, "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/2/ingredients/0/quantityVariations/0/translations" } }, { "$id": "#/items/137/variations/45/product/ingredientGroups/2/ingredients/0/quantityVariations/1", "name": "", "quantity": 1, "price": 0, "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/2/ingredients/0/quantityVariations/1/translations" } } ], "index": 0, "imageLink": "https://cdn.dodostatic.net/static/Img/Ingredients/000D3A262427A95111E9DBAD10EF7B80", "mediaServiceImageId": "11ee7f0cea4532c7810dcc72adc6229f", "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/2/ingredients/0/translations", "Name": { "$ref": "#/items/0/variations/0/product/ingredientGroups/3/ingredients/0/translations/Name" } } } ], "index": 4, "additionalData": [], "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/2/translations", "Name": { "$ref": "#/items/137/variations/15/product/ingredientGroups/2/translations/Name" } } }, { "$id": "#/items/137/variations/45/product/ingredientGroups/3", "code": "yxqo", "isBasis": false, "name": "соус ранч", "choiceType": "None", "totalQuantityMin": 1, "totalQuantityMax": 1, "ingredients": [ { "$id": "#/items/137/variations/45/product/ingredientGroups/3/ingredients/0", "materialTypeId": "000d3a27d5a4a94411e87ab4490abb7d", "name": "Соус ранч", "quantity": 1, "quantityVariations": [ { "$id": "#/items/137/variations/45/product/ingredientGroups/3/ingredients/0/quantityVariations/0", "name": "", "quantity": 1, "price": 0, "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/3/ingredients/0/quantityVariations/0/translations" } } ], "index": 0, "imageLink": "https://cdn.dodostatic.net/static/Img/Ingredients/000D3A262427A95111E9DBADA4622538", "mediaServiceImageId": "11ee7f0cec92c897b88f28646c5dc9f5", "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/3/ingredients/0/translations", "Name": { "$ref": "#/items/1/variations/0/product/ingredientGroups/1/ingredients/0/translations/Name" } } } ], "index": 5, "additionalData": [], "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/3/translations", "Name": { "$ref": "#/items/137/variations/15/product/ingredientGroups/3/translations/Name" } } }, { "$id": "#/items/137/variations/45/product/ingredientGroups/4", "code": "rqjc", "isBasis": false, "name": "томаты", "choiceType": "Single", "totalQuantityMin": 0, "totalQuantityMax": 1, "ingredients": [ { "$id": "#/items/137/variations/45/product/ingredientGroups/4/ingredients/0", "materialTypeId": "000d3a2479f7a94411e87ab46e313d55", "name": "Томаты", "quantity": 1, "quantityVariations": [ { "$id": "#/items/137/variations/45/product/ingredientGroups/4/ingredients/0/quantityVariations/0", "name": "", "quantity": 0, "price": 0, "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/4/ingredients/0/quantityVariations/0/translations" } }, { "$id": "#/items/137/variations/45/product/ingredientGroups/4/ingredients/0/quantityVariations/1", "name": "", "quantity": 1, "price": 0, "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/4/ingredients/0/quantityVariations/1/translations" } } ], "index": 0, "imageLink": "https://cdn.dodostatic.net/static/Img/Ingredients/000D3A262427A95111E9DBAD64FE3988", "mediaServiceImageId": "11ee7f0ceb83eed585e1bdc4c0cc1c46", "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/4/ingredients/0/translations", "Name": { "$ref": "#/items/0/variations/0/product/ingredientGroups/7/ingredients/14/translations/Name" } } } ], "index": 6, "additionalData": [], "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/4/translations", "Name": { "$ref": "#/items/137/variations/15/product/ingredientGroups/4/translations/Name" } } }, { "$id": "#/items/137/variations/45/product/ingredientGroups/5", "code": "vsnv", "isBasis": false, "name": "красный лук", "choiceType": "Single", "totalQuantityMin": 0, "totalQuantityMax": 1, "ingredients": [ { "$id": "#/items/137/variations/45/product/ingredientGroups/5/ingredients/0", "materialTypeId": "000d3a262427a94911e884454e1c1273", "name": "Красный лук", "quantity": 1, "quantityVariations": [ { "$id": "#/items/137/variations/45/product/ingredientGroups/5/ingredients/0/quantityVariations/0", "name": "", "quantity": 0, "price": 0, "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/5/ingredients/0/quantityVariations/0/translations" } }, { "$id": "#/items/137/variations/45/product/ingredientGroups/5/ingredients/0/quantityVariations/1", "name": "", "quantity": 1, "price": 0, "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/5/ingredients/0/quantityVariations/1/translations" } } ], "index": 0, "imageLink": "https://cdn.dodostatic.net/static/Img/Ingredients/000D3A219740A95611E9DBAD369D06C3", "mediaServiceImageId": "11ee7f0ceacd0886b1a121fd1faf90d0", "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/5/ingredients/0/translations", "Name": { "$ref": "#/items/0/variations/0/product/ingredientGroups/5/ingredients/0/translations/Name" } } } ], "index": 7, "additionalData": [], "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/5/translations", "Name": { "$ref": "#/items/137/variations/15/product/ingredientGroups/5/translations/Name" } } }, { "$id": "#/items/137/variations/45/product/ingredientGroups/6", "code": "javt", "isBasis": false, "name": "чеснок", "choiceType": "Single", "totalQuantityMin": 0, "totalQuantityMax": 1, "ingredients": [ { "$id": "#/items/137/variations/45/product/ingredientGroups/6/ingredients/0", "materialTypeId": "11eaa8beac20e36b86bbcdb34fe769c0", "name": "Чеснок", "quantity": 1, "quantityVariations": [ { "$id": "#/items/137/variations/45/product/ingredientGroups/6/ingredients/0/quantityVariations/0", "name": "", "quantity": 0, "price": 0, "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/6/ingredients/0/quantityVariations/0/translations" } }, { "$id": "#/items/137/variations/45/product/ingredientGroups/6/ingredients/0/quantityVariations/1", "name": "", "quantity": 1, "price": 0, "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/6/ingredients/0/quantityVariations/1/translations" } } ], "index": 0, "imageLink": "https://cdn.dodostatic.net/static/Img/Ingredients/6cb19808b9fe451b80067b8cbf16ebb6.png", "mediaServiceImageId": "11ee7f0ced54b4ed864181c8cd0fd7f6", "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/6/ingredients/0/translations", "Name": { "$ref": "#/items/1/variations/0/product/ingredientGroups/6/ingredients/0/translations/Name" } } } ], "index": 8, "additionalData": [], "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/6/translations", "Name": { "$ref": "#/items/137/variations/15/product/ingredientGroups/6/translations/Name" } } }, { "$id": "#/items/137/variations/45/product/ingredientGroups/7", "code": "rxek", "isBasis": false, "name": "моцарелла", "choiceType": "None", "totalQuantityMin": 1, "totalQuantityMax": 1, "ingredients": [ { "$id": "#/items/137/variations/45/product/ingredientGroups/7/ingredients/0", "materialTypeId": "000d3a27d5a4a94411e87ab2dd132cf3", "name": "Моцарелла", "quantity": 1, "quantityVariations": [ { "$id": "#/items/137/variations/45/product/ingredientGroups/7/ingredients/0/quantityVariations/0", "name": "", "quantity": 1, "price": 0, "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/7/ingredients/0/quantityVariations/0/translations" } } ], "index": 0, "imageLink": "https://cdn.dodostatic.net/static/Img/Ingredients/74c62256e82a4a78a646251490446369.png", "mediaServiceImageId": "11ee7f0ceaae1cc98754590de178c0f7", "translations": { "$id": "#/items/137/variations/45/product/ingredientGroups/7/ingredients/0/translations", "Name": { "$ref": "#/items/0/variations/0/product/ingredientGroups/2/ingredients/0/translations/Name" } } } ], - Assistant
Похоже, у вас есть длинный JSON-объект, который содержит сложные вложенные структуры данных. Если цель — извлечь информацию о пиццах из этого JSON, важно понять его структуру. Из предоставленных фрагментов видно, что у каждого элемента, возможно, есть ключи, такие как
'trait'или'product', которые могут указывать на то, является ли продукт пиццей.Давайте попробуем сформулировать код, который будет адаптироваться к текущей структуре и фильтровать данные по пиццам. Я предположу, что вас интересует информация о пиццах, содержащаяся в каждом продукте:
- Основа данных для пиццы обнаруживается по признаку
'pizza': trueв ключе'traits'. - Вас могут интересовать ключи
'name','price', и'ingredients'.
Исходя из этого, вот как вы можете переписать фильтрацию:
import json def load_menu_from_file(filename): with open(filename, 'r', encoding='utf-8') as file: return json.load(file) def filter_pizzas(menu_data): pizzas = [] for item in menu_data.get('items', []): # Предполагается, что данные находятся под ключом 'items' for variation in item.get('variations', []): product = variation.get('product', {}) traits = product.get('traits', {}) if traits.get('pizza', False): # Проверяем, является ли продукт пиццей pizza_info = { 'name': product.get('name'), 'price': product.get('price'), 'ingredients': [ingredient['name'] for group in product.get('ingredientGroups', []) for ingredient in group.get('ingredients', [])] } pizzas.append(pizza_info) return pizzas def save_to_json(data, filename): with open(filename, 'w', encoding='utf-8') as file: json.dump(data, file, ensure_ascii=False, indent=4) def main(): input_filename = 'local_menu.json' # Укажите здесь имя вашего файла с меню output_filename = 'filtered_pizzas.json' menu_data = load_menu_from_file(input_filename) pizzas = filter_pizzas(menu_data) save_to_json(pizzas, output_filename) print(f"Filtered pizzas have been saved to {output_filename}") if __name__ == "__main__": main()Пояснения к коду:
load_menu_from_file: Загружает JSON-данные из файла.filter_pizzas: Пробегается по всем элементам и их вариациям.- Осуществляет проверку на наличие продукта, который помечен как пицца —
traitsсодержит'pizza': true. - Собирает информацию о названии, цене и списке ингредиентов для каждой пиццы.
- Осуществляет проверку на наличие продукта, который помечен как пицца —
save_to_json: Сохраняет отфильтрованные данные пицц в файлfiltered_pizzas.json.
Задайте правильную структуру данных и ключи, ориентируясь на фактическую структуру вашего JSON, если она отличается от предложенной в коде. Если у вас будут дополнительные вопросы, пожалуйста, дайте знать!
- Основа данных для пиццы обнаруживается по признаку