【发布时间】:2019-11-21 00:11:03
【问题描述】:
我有这个 csv:
product_id, width, height
14866, 200, 200
14866, 300, 300
我正在使用 csv 导入和 json 来尝试创建一个 json 来发出 api 请求。
这就是我的python现在的样子:
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))
这会导致这个 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"
}
]
}
}
]
}
我想要实现的 json 是将相同 product_id 的尺寸嵌套如下:
{
"sizes": [
{
"id": 14866,
"product": {
"product_creative_size_attributes": [
{
"width": "200",
"height": "200"
},
{
"width": "300",
"height": "300"
}
]
}
}
]
}
【问题讨论】:
-
您希望它们按
product_id分组吗? -
考虑分两个阶段填充输出。首先识别唯一的
product_ids,并为每个创建{'id': <product_id>, 'product': {'product_creative_size_attributes': []}}。然后循环遍历每个 csv 行,再次附加到特定产品的嵌套数组。 -
@Boris 是的,我希望它们按 product_id 分组 - 但我需要将“product_creative_size_attributes”嵌套在“product”下
-
@FraggaMuffin 我是一个超级 python 初学者 - 你能告诉我一个示例 python 来显示你的建议吗?
-
请注意,有两个不同的值与
"product"相关联——哪一个应该“获胜”并最终出现在组合结果中?