Python JSON数据处理:将数组元素包装为product键并重组结构
JSON结构转换问题解决
原始JSON结构
[ { "sku": "2", "view_code": "english", "short_description": "xy", "product_type": "simple", "attribute_set_code": "4" }, { "sku": "1", "view_code": "english", "short_description": "xy", "product_type": "simple", "attribute_set_code": "4" } ]
注意:你想要的目标结构不合法
你给出的目标JSON里,同一个对象包含多个同名的"product"键,这不符合JSON规范——解析器会直接覆盖重复键,最终只会保留最后一个product对象,无法达到你预期的效果。
推荐的合法目标结构
如果要把每个商品对象包装在product键下,合理的结构有两种:
结构一:数组内每个元素为含product的对象
[ { "product": { "sku": "2", "view_code": "english", "short_description": "xy", "product_type": "simple", "attribute_set_code": "4" } }, { "product": { "sku": "1", "view_code": "english", "short_description": "xy", "product_type": "simple", "attribute_set_code": "4" } } ]
结构二:单对象内包含products数组
{ "products": [ { "sku": "2", "view_code": "english", "short_description": "xy", "product_type": "simple", "attribute_set_code": "4" }, { "sku": "1", "view_code": "english", "short_description": "xy", "product_type": "simple", "attribute_set_code": "4" } ] }
代码实现(以Python为例)
无需转成字符串循环处理,直接用JSON解析库操作数据结构更可靠:
实现结构一
import json # 读取原始JSON文件 with open('input.json', 'r', encoding='utf-8') as f: raw_data = json.load(f) # 转换结构 transformed_data = [{"product": item} for item in raw_data] # 写入新JSON文件 with open('output1.json', 'w', encoding='utf-8') as f: json.dump(transformed_data, f, indent=2, ensure_ascii=False)
实现结构二
import json with open('input.json', 'r', encoding='utf-8') as f: raw_data = json.load(f) transformed_data = {"products": raw_data} with open('output2.json', 'w', encoding='utf-8') as f: json.dump(transformed_data, f, indent=2, ensure_ascii=False)
你之前方法出错的原因
直接操作字符串处理JSON极易出现格式错误,比如引号不匹配、逗号位置错误等。正确做法是用JSON解析库将JSON转为编程语言的原生数据结构(列表、字典),修改结构后再转回JSON字符串,能完全保证格式合法性。
内容的提问来源于stack exchange,提问作者wayx
相关产品推荐
相关产品推荐

