如何遍历 CSV 文件并仅将具有特定值的 csv 行写入 JSON 中的另一个文件?

how to iterate through a CSV file and write to another file in JSON only the csv rows with a certain value?

我正在尝试获取一个 csv 文件并遍历它,只获取具有蓝色类别的行并将它们写入 JSON 文件。到目前为止,我已经创建了一个程序,它获取所有 csv 行并写入 JSON 文件。我不太确定如何 select 仅具有特定值的特定 csv 行。 这是具有此输出的程序

import csv
import json


def csv_to_json(csvFilePath, jsonFilePath):
    jsonArray = []

    with open(csvFilePath, encoding='utf-8') as csvf:
        csvReader = csv.DictReader(csvf)

        for row in csvReader:
            jsonArray.append(row)

    with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
        jsonString = json.dumps(jsonArray, indent=4)
        jsonf.write(jsonString)


csvFilePath = r'csv_example.csv'
jsonFilePath = r'reader.json'
csv_to_json(csvFilePath, jsonFileP

输出:

[
    {
        "id": "1",
        "category": "blue",
        "password": "hi"
    },
    {
        "id": "2",
        "category": "red",
        "password": "no"
    },
    {
        "id": "3",
        "category": "blue",
        "password": "lol"
    },
    {
        "id": "4",
        "category": "yellow",
        "password": "yo"
    },
    {
        "id": "5",
        "category": "yellow",
        "password": "sup"
    },
    {
        "id": "6",
        "category": "orange",
        "password": "hello"
    },
    {
        "id": "7",
        "category": "blue",
        "password": "yeah"
    }
]

以这个csv文件为例

"id","category","password"
"1","blue","hi"
"2","red","no"
"3","blue","lol"
"4","yellow","yo"
"5","yellow","sup"
"6","orange","hello"
"7","blue","yeah"

我该如何做到只有类别为蓝色的行才能写入 JSON 文件。我试过了

if row.category == 'blue'

但这显然行不通

由于 DictReader 将每一行都转换为 python 字典,因此您只需在一个位置扩展代码。

for row in csvReader:
   if row["category"] != "blue":
      continue
   jsonArray.append(row)

if row["category"] != "blue":检查行中的键类别的值是否不是蓝色。 如果该行不是蓝色,代码将 continue 与下一行