写入CSV文件时,JSON列的引号字符不正确

doinxwow  于 2023-09-27  发布在  其他
关注(0)|答案(1)|浏览(76)

我正在从一个数据集合中编写一个新的CSV文件,稍后我想将其导入SQL数据库。
数据应该以JSON格式存储在“size”和“colors”列中。
如何将列括在单引号中,将括号中的数据括在双引号中?

with open("export.csv", "w", newline="") as csvfile:
    # Create a CSV writer using the field/column names
    writer = csv.DictWriter(
        csvfile,
        fieldnames=csv_fields,
    )
    # Write the header row (column names)
    writer.writeheader()
    for key in dict_products:
        print(dict_products[key])
        writer.writerow(dict_products[key])

这就是现在正在创造的。

id,prodcategory_id,name,featured,image_1,image_2,image_3,image_4,colors,sizes,article_number,price,manufacturer_id
NULL,521,,0,521010000-1.jpg,,,,['1'],"['39', '41', '42', '43', '44', '45', '46']",521010000,6990,582
NULL,115,Women Court Sho,0,115130000-1.jpg,,,,['13'],"['36', '37', '38', '39', '40', '41']",115130000,4990,32

应该是这样的

id,prodcategory_id,name,featured,image_1,image_2,image_3,image_4,colors,sizes,article_number,price,manufacturer_id
NULL,521,,0,521010000-1.jpg,,,,["1"],'["39", "41", "42", "43", "44", "45", "46"]',521010000,6990,582
NULL,115,Women Court Sho,0,115130000-1.jpg,,,,["13"],'["36", "37", "38", "39", "40", "41"]',115130000,4990,32
kxkpmulp

kxkpmulp1#

对我来说,它看起来像dict_products是一个字典,有一个键和你想要的csv行作为值。colorssizes键看起来像列表。要获得引用的结果,您需要对每个值使用json.dumps。然后在写csv时,指定单引号(')作为引号字符。
https://onlinegdb.com/PBKLPNoar

import csv, json

dict_products = {
'key1': {'id': 'NULL',
  'prodcategory_id': '521',
  'name': '',
  'featured': '0',
  'image_1': '521010000-1.jpg',
  'image_2': '',
  'image_3': '',
  'image_4': '',
  'colors': ['1'],
  'sizes': ['39', '41', '42', '43', '44', '45', '46'],
  'article_number': '521010000',
  'price': '6990',
  'manufacturer_id': '582'},
'key2': {'id': 'NULL',
  'prodcategory_id': '115',
  'name': 'Women Court Sho',
  'featured': '0',
  'image_1': '115130000-1.jpg',
  'image_2': '',
  'image_3': '',
  'image_4': '',
  'colors': ['13'],
  'sizes': ['36', '37', '38', '39', '40', '41'],
  'article_number': '115130000',
  'price': '4990',
  'manufacturer_id': '32'}
}
csv_fields = list(dict_products['key1'].keys())

with open("export.csv", "w", newline="") as csvfile:
    writer = csv.DictWriter(
        csvfile,
        fieldnames=csv_fields,
        quotechar='\''
    )
    writer.writeheader()
    for key in dict_products:
        color, sizes = dict_products[key]['colors'], dict_products[key]['sizes']
        dict_products[key]['colors'] = json.dumps(color)
        dict_products[key]['sizes'] = json.dumps(sizes)
        writer.writerow(dict_products[key])

相关问题