【问题标题】:CSV to JSON, creating an array from columnsCSV 到 JSON,从列创建数组
【发布时间】:2020-01-24 02:36:43
【问题描述】:

我有如下示例 csv 数据:

id,hex1,hex2,hex3,hex4,hex5
388,#442c1c,#927450,#664c31,#22110c,
387,#6a442f,#826349,,,
1733,#4d432e,#75623f,,,
1728,#393e46,#5f4433,#ad7a52,#362c28,#a76042

我想从这个 csv 创建 JSON 数据,看起来像这样:

{
  "images":[
    {
      "colors": [
        "#442c1c",
        "#2f4f4f",
        "#927450",
        "#696969",
        "#664c31",
        "#556b2f"
      ],
      "id": "388"
    }
  ]
}

每一行都应采用第一列 (id) 并创建一个字典/数组(抱歉,不确定术语是否正确),其中包含该行中的十六进制值。 Python 是我最熟悉的语言,所以我更喜欢用它来创建我的 JSON。

谁能建议一些起点?

提前谢谢你。

【问题讨论】:

    标签: python arrays json csv dictionary


    【解决方案1】:

    您可以使用以下基本上是列表理解的内容:

    import csv
    
    with open('file.csv', mode='r') as csv_file:
        reader = csv.DictReader(csv_file)
        next(reader, None)  # skip the header
        # id,hex1,hex2,hex3,hex4,hex5
        images = [{'colors': [row[f'hex{n}'] for n in range(1, 6) if row[f'hex{n}'] != ''], 'id': row["id"]} for row in reader]
    
    d = {'images': images}
    

    d 将包含您想要的字典:

    {'images': [{'colors': ['#6a442f', '#826349'], 'id': '387'},
                {'colors': ['#4d432e', '#75623f'], 'id': '1733'},
                {'colors': ['#393e46', '#5f4433', '#ad7a52', '#362c28', '#a76042'],
                 'id': '1728'}]}
    

    【讨论】:

      猜你喜欢
      • 2017-02-03
      • 2022-11-03
      • 2014-11-04
      • 1970-01-01
      • 2019-03-06
      • 2013-11-06
      • 2021-07-19
      • 1970-01-01
      • 2012-10-14
      相关资源
      最近更新 更多