仅当CSV中存在所有值时,才将CSV输出为JSON

时间:2020-10-01 02:35:14

标签: python json pandas dataframe csv

我有一个串联的CSV文件,我正在尝试将其输出为JSON格式。我应该如何实现仅将CSV文件转换为所有字段都具有值的JSON对象的逻辑?

import glob , os
import pandas as pd
import json
import csv



with open('some.csv', 'r', newline='') as csvfile, \
     open('output.json', 'w') as jsonfile:

    for row in csv.DictReader(csvfile):
        restructured = {
            'STATION_CODE': row['STORE_CODE'],
            'id': row['ARTICLE_ID'],
            'name': row['ITEM_NAME'],
            'data':
              {
            # fieldname: value for (fieldname, value) in row.items()
                    'STORE_CODE': row['STORE_CODE'],
                    'ARTICLE_ID': row['ARTICLE_ID'],
                    'ITEM_NAME': row['ITEM_NAME'],
                    'BARCODE': row['BARCODE'],
                    'SALE_PRICE': row['SALE_PRICE'],
                    'LIST_PRICE': row['LIST_PRICE'],
                    'UNIT_PRICE': row['UNIT_PRICE'],
                  }
        }
        json.dump(restructured, jsonfile, indent=4)
        jsonfile.write('\n')

当前,这会将CSV文件中的所有值提供到JSON输出中,这是意外行为。有关如何更正此问题的任何投入?

1 个答案:

答案 0 :(得分:0)

首先,我遍历CSV的所有元素,并将其添加到JSON array中。如果有任何行元素value is empty,则该行将为ignored。将所有行保存在JSON array中后,我会将其输出到JSON文件

import json
import csv

csvjsonarr = []

with open('some.csv', 'r', newline='') as csvfile :

    for row in csv.DictReader(csvfile):
        
        hasemptyvalues = False

        for rowidx in row :
            if row[rowidx] == "" :
                hasemptyvalues = True
                break

        if hasemptyvalues == True :
            continue

        restructured = {
            'STATION_CODE': row['STORE_CODE'],
            'id': row['ARTICLE_ID'],
            'name': row['ITEM_NAME'],
            'data': {
                'STORE_CODE': row['STORE_CODE'],
                'ARTICLE_ID': row['ARTICLE_ID'],
                'ITEM_NAME': row['ITEM_NAME'],
                'BARCODE': row['BARCODE'],
                'SALE_PRICE': row['SALE_PRICE'],
                'LIST_PRICE': row['LIST_PRICE'],
                'UNIT_PRICE': row['UNIT_PRICE'],
            }
        }
        csvjsonarr.append(restructured)
        
if len(csvjsonarr) > 0 :
    with open('output.json', 'w') as jsonfile :
        json.dump(csvjsonarr, jsonfile, indent=4)