【问题标题】:CSV to JSON output only if all values are present in CSV仅当所有值都存在于 CSV 中时,才输出 CSV 到 JSON
【发布时间】:2021-01-16 18:13:55
【问题描述】:

我有一个连接的 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 输出中,这是意外行为。有关如何纠正此问题的任何意见?

【问题讨论】:

  • 要清楚,如果CSV 文件在any row 上有empty value; JSON 文件应该 not be outputted at all 或者如果 CSV 行有任何空值; only those rows 不应该是 outputted to the JSON file
  • @ChathurangaK 如果 CSV 行有一个空值,则只有那些行不应输出到 JSON 文件。感谢您的澄清!

标签: python json pandas dataframe csv


【解决方案1】:

首先我遍历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)

【讨论】:

    猜你喜欢
    • 2017-03-20
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 2022-01-09
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多