I have this csv:
product_id, width, height
14866, 200, 200
14866, 300, 300
I'm using the csv import and json to try to create a json to make a api request.
This is what my python looks like right now:
import csv
import json
json_dict = {}
results = []
with open('sizes.csv',encoding='utf-8-sig') as f:
for row in csv.DictReader(f,):
results.append(
{'id': int(row['product_id']),
'product':
{'product_creative_size_attributes':[{'width':str(row['width']),'height': str(row['height'])}]}})
json_dict["sizes"] = results
output_json = print(json.dumps(json_dict,indent=4))
Which results in this json:
{
"sizes": [
{
"id": 14866,
"product": {
"product_creative_size_attributes": [
{
"width": "200",
"height": "200"
}
]
}
},
{
"id": 14866,
"product": {
"gam_product_creative_size_attributes": [
{
"width": "300",
"height": "300"
}
]
}
}
]
}
the json that i'm trying to achieve is to have the sizes for the same product_id to be nested like this:
{
"sizes": [
{
"id": 14866,
"product": {
"product_creative_size_attributes": [
{
"width": "200",
"height": "200"
},
{
"width": "300",
"height": "300"
}
]
}
}
]
}
product_id?product_ids, and create{'id': <product_id>, 'product': {'product_creative_size_attributes': []}}for each one. Then loop through each csv row again appending to the particular product's nested array."product"— which one should "win" and end up in the combined result?