如何在将csv文件转换为json格式时根据某些条件检查特定的字段值 [英] How to check for specific field values based on some condition while converting csv file to json format

查看:194
本文介绍了如何在将csv文件转换为json格式时根据某些条件检查特定的字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是在python中将csv文件转换为json格式的代码. 我有两个字段推荐"和评级".基于推荐值,我需要设置等级字段的值,例如如果推荐为1,则等级为= 1,反之亦然.有了答案,我得到的只是一个记录条目的输出,而不是所有记录的输出.我认为这是最重要的.我是否需要为此创建单独的列表,并将每个记录条目追加到列表以获取所有记录的输出. 这是更新的代码:

Below is the code to convert csv file to json format in python. I have two fields 'recommendation' and 'rating'. Based on the recommendation value I need to set the value for rating field like if recommendation is 1 then rating =1 and vice versa. With the answer I got I'm getting output for only one record entry instead of getting all the records. I think it's overriding. Do I need to create separate list for that and append each record entry to the list to get the output for all records. here's the updated code:

def main(input_file):
csv_rows = []
with open(input_file, 'r') as csvfile:
    reader = csv.DictReader(csvfile, delimiter='|')
    title = reader.fieldnames
    for row in reader:
        entry = OrderedDict()
        for field in title:
            entry[field] = row[field]
        [c.update({'RATING': c['RECOMMENDATIONS']}) for c in reader]
        csv_rows.append(entry)

with open(json_file, 'w') as f:
    json.dump(csv_rows, f, sort_keys=True, indent=4, ensure_ascii=False)
    f.write('\n')

我想创建如下的嵌套格式:

I want to create the nested format like the below:

"rating": {
"user_rating": {
  "rating": 1
},
"recommended": {
  "rating": 1
}

推荐答案

使用csv.DictReader读入文件后,将有字典列表.由于您现在要设置值,因此是简单的dict操作.有几种方法,其中一种是:

After you've read the file in, using the csv.DictReader, you'll have a list of dicts. Since you want to set the values now, it's a simple dict manipulation. There are several ways, of which one is:

[c.update({'rating': c['recommendation']}) for c in read_csvDictReader]

希望有帮助.

这篇关于如何在将csv文件转换为json格式时根据某些条件检查特定的字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆