【发布时间】: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