代码之家  ›  专栏  ›  技术社区  ›  Biplov

基于JSON字典键的CSV头

  •  0
  • Biplov  · 技术社区  · 5 年前

    我有一个这样的JSON例如:

    [
        {
            'name':'test1',
            'random1':'random_1_value'
        },
        {
            'name':'test2',
            'random2':'random_2_value'
            'random4':'random_4_value'
        },
        {
            'name':'test3',
            'random3':'random_3_value'
        },
    ]
    

    我想转换这个JSON并基于字典键构造CSV头。然后分别填充每一行。预期产量:

    name, random1, random2, random4, random3
    test1, random_1_value
    test2, ,random_2_value, random_4_value, ,
    test3, , , , random_3_value
    

    data = json.loads(open('output_data.json').read())
    csvwriter = csv.writer(open("output.csv", "w"))
    count = 0
    for emp in data:
        if count == 0:
            header = emp.keys()
            csvwriter.writerow(header)
            count += 1
        csvwriter.writerow(emp.values())
    
    0 回复  |  直到 5 年前
        1
  •  1
  •   snakecharmerb    5 年前

    您可以使用 collections csv 标准库中的模块执行此操作。

    collections.OrderedDict 获取列名的显示顺序。

    我们用一个 OrderedDict 这样代码就可以在3.7之前的Python版本中使用。从Python3.7开始 那些普通的字典记得钥匙的插入顺序。如果您的代码只由Python3.7+运行,则可以使用 dict 内置而不是 .

    headers = collections.OrderedDict((key, None) for dict_ in data for key in dict_) 
    

    csv.DictWriter 将数据中的每个字典写入输出文件。 DictWriter

    with open('output.csv', 'w', newlines='') as f:
        writer = csv.DictWriter(f, fieldnames=headers)
        # Write the column names to file.
        writer.writeheader()
        # Write the data to file.
        writer.writerows(data)
    
        2
  •  0
  •   aydow    5 年前

    你应该使用 with 操作员读取和写入文件时。 See here

    # Open the JSON file
    >>> with open('csv.json') as f:
    ...     data = json.load(f)
    
    # Get the column names
    >>> col = [k for d in data for k in d]
    
    # Create a matrix of the data
    >>> matrix = [[d['name']] + [d.get(c, '') for c in col] for d in data]
    
    >>> csv_data = [['name'] + col] + matrix
    
    >>> with open('json.csv', 'w') as f:
    ...     writer = csv.writer(f)
    ...     writer.writerows(csv_data)