请求协助:将Shopify API嵌套JSON转换为CSV
Hey there! Let's fix that error and get your Shopify nested JSON flattened into CSV correctly. The problem in your code is a common pitfall when working with nested data—let's break it down first.
What's Causing the Error?
Your original code loads the JSON into x, which is a single dictionary representing the product. When you run for x in x:, you're actually looping over the string keys of that dictionary (like "id", "title", "variants"), not the data you care about. That's why you get TypeError: string indices must be integers—you're trying to use string keys on a string itself (e.g., "id"["id"]), which doesn't make sense.
Fixed Code to Flatten the JSON
What you need to do is loop through the variants list inside your product JSON, and pair each variant with the parent product's details (for the first row) or use null values for subsequent rows as you wanted. Here's the corrected code:
import csv import json # Load the Shopify product JSON with open('product.json') as file: product = json.load(file) # Write the flattened data to CSV with open("test.csv", "w", newline='', encoding='utf-8') as csv_file: writer = csv.writer(csv_file) # Write the header row writer.writerow(["id", "title", "option1", "grams"]) # Grab the parent product's core details once parent_id = product["id"] parent_title = product["title"] # Loop through each variant in the product for index, variant in enumerate(product["variants"]): # Use parent details for the first variant; use "null" for others row_id = parent_id if index == 0 else "null" row_title = parent_title if index == 0 else "null" # Extract variant-specific fields (use .get() to handle missing keys safely) option1 = variant.get("option1", "null") grams = variant.get("grams", "null") # Write the row to CSV writer.writerow([row_id, row_title, option1, grams])
How This Works
- We renamed the loaded JSON variable to
productto avoid overwriting it in loops (a clearer practice than usingx). - Using
newline=''when opening the CSV file prevents extra blank lines in the output, a common quirk with Python'scsvmodule. - We loop through the
variantslist directly—this is where the individual product options (Small/Medium) are stored. - For the first variant, we use the parent product's
idandtitle; for every other variant, we write"null"to match your desired output. variant.get()safely retrieves values (if a key ever goes missing, it defaults to"null"instead of throwing an error).
Expected Output
Running this code will produce exactly the CSV format you wanted:
id,title,option1,grams 788032119674292922,Example T-Shirt,Small,200 null,null,Medium,200
内容的提问来源于stack exchange,提问作者Tim Silver

