Created
February 23, 2024 20:58
-
-
Save stoph/598aeb3a56775e26be8e5027c707ecc7 to your computer and use it in GitHub Desktop.
Convert Shopify's products.json to csv file for import
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://<shopify.store.com>/products.json?limit=250 (defaults to 30) | |
import csv | |
import json | |
def convert_json_to_csv(json_file, csv_file): | |
with open(json_file, 'r', encoding='utf-8') as file: | |
data = json.load(file) | |
products = data['products'] | |
with open(csv_file, mode='w', newline='', encoding='utf-8') as file: | |
writer = csv.writer(file) | |
writer.writerow(['Handle', 'Title', 'Body (HTML)', 'Vendor', 'Type', 'Tags', 'Published', 'Option1 Name', 'Option1 Value', 'Variant SKU', 'Variant Grams', 'Variant Inventory Qty', 'Variant Price', 'Image Src']) | |
for product in products: | |
handle = product['handle'] | |
title = product['title'] | |
body_html = product['body_html'] | |
vendor = product['vendor'] | |
product_type = product['product_type'] | |
tags = ', '.join(['mecum'] + product['tags']) | |
published = 'TRUE' if product['published_at'] else 'FALSE' | |
# Ensure there's at least one variant for images | |
variants_or_dummy = product['variants'] if product['variants'] else [{}] | |
max_length = max(len(product['images']), len(variants_or_dummy)) | |
for i in range(max_length): | |
variant = variants_or_dummy[i] if i < len(product['variants']) else {} | |
image_src = product['images'][i]['src'] if i < len(product['images']) else '' | |
option1_name = variant.get('option1', None) | |
option1_value = variant.get('title', '') | |
sku = variant.get('sku', '') | |
grams = variant.get('grams', '') | |
inventory_qty = variant.get('inventory_quantity', '0') if 'inventory_quantity' in variant else '0' | |
price = variant.get('price', '') | |
writer.writerow([handle, title, body_html, vendor, product_type, tags, published, option1_name, option1_value, sku, grams, inventory_qty, price, image_src]) | |
convert_json_to_csv('products.json', 'products.csv') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment