Skip to content

Instantly share code, notes, and snippets.

@mvark
Created April 6, 2025 15:50
Show Gist options
  • Save mvark/88fc758e6f346a8b3471979afff82fca to your computer and use it in GitHub Desktop.
Save mvark/88fc758e6f346a8b3471979afff82fca to your computer and use it in GitHub Desktop.
Code sample from ChatGPT to generate a CSV file containing paneer products from the Open Food Facts India database with complete and non-zero nutritional information
import requests
import csv
# API endpoint with relevant fields
api_url = (
"https://in.openfoodfacts.org/facets/categories/paneer?"
"fields=code,brands,quantity,product_name,energy-kcal_100g,carbohydrates_100g,"
"fat_100g,calcium_100g,cholesterol_100g,saturated-fat_100g,proteins_100g,"
"salt_100g,sugars_100g,fiber_100g,nutriscore_grade,nova_group&json=1"
)
response = requests.get(api_url)
data = response.json()
# Filter for products with non-zero key nutrients
required_fields = ['energy-kcal_100g', 'carbohydrates_100g', 'fat_100g', 'proteins_100g']
filtered_products = []
for product in data.get('products', []):
try:
if all(float(product.get(field, 0)) > 0 for field in required_fields):
filtered_products.append(product)
except (ValueError, TypeError):
continue
# Determine all fields present
all_fields = list({key for product in filtered_products for key in product.keys()})
# Write to CSV
with open("filtered_paneer_products_full_fields.csv", mode='w', newline='', encoding='utf-8') as file:
writer = csv.DictWriter(file, fieldnames=all_fields)
writer.writeheader()
for product in filtered_products:
writer.writerow({field: product.get(field, '') for field in all_fields})
print(f"Saved {len(filtered_products)} records to 'filtered_paneer_products_full_fields.csv'")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment