我从csv文件中读取后向json添加一个新字段,如何将值添加到json中

时间:2017-06-26 23:52:28

标签: python json csv

我只有一周大的python所以请不要介意我的无知,我正在读取一个csv文件并从中创建一个json文件,同时这样做我正在添加一个新字段 JerseyNumber 到我的field_names,因为这个值在csv中不存在,它被存储为null,有什么方法可以填充这个字段,所以我的行动方针是有一个数字列表,如 -

JERSEYNUMBERS = ["1","2","3","4","5","6","7"] 

和    使用 -

从中添加随机值
"".join(random.sample(JERSEYNUMBERS,2))

但我无法找到使用json的方法,因为使用restval="".join(random.sample(JERSEYNUMBERS,2) dos不会给出随机值并更新所有Jersey编号的相同值。

我的csv到json的函数 -

def csv_to_json (csv_file_name_str, json_file_name_str):
    try:
        logging.info("converting {} to {}".format(csv_file_name_str, json_file_name_str))
        csv_file = open(csv_file_name_str, "r")
        json_file = open(json_file_name_str, "w")

        field_names = ["Name", "Height", "SoccerExperience", "GuardianName", "JerseyNumber"]
        reader = csv.DictReader(csv_file, field_names, restval="".join(random.sample(JERSEYNUMBERS,2)))
        logging.info("Conversion finish.")
        out = '{\n "Players": [\n\t'+ ',\n\t'.join([json.dumps(row) for row in reader]) + '\n]\n}'
        json_file.write(out)
        return json_file_name_str
    except (OSError, IOError, TypeError) as e:
        logging.error("csv to json conversion failed: Caused by -> {}".format(e))

我在JerseyNumbers中使用空值的json文件(这是我的测试数据不是真人) -

{
 "Players": [
    {"Name": "Name", "Height": "Height (inches)", "SoccerExperience": "Soccer Experience", "GuardianName": "Guardian Name(s)", "JerseyNumber": null},
    {"Name": "Joe Smith", "Height": "42", "SoccerExperience": "YES", "GuardianName": "Jim and Jan Smith", "JerseyNumber": null},
    {"Name": "Jill Tanner", "Height": "36", "SoccerExperience": "YES", "GuardianName": "Clara Tanner", "JerseyNumber": null},
    {"Name": "Bill Bon", "Height": "43", "SoccerExperience": "YES", "GuardianName": "Sara and Jenny Bon", "JerseyNumber": null},
    {"Name": "Eva Gordon", "Height": "45", "SoccerExperience": "NO", "GuardianName": "Wendy and Mike Gordon", "JerseyNumber": null},
    {"Name": "Matt Gill", "Height": "40", "SoccerExperience": "NO", "GuardianName": "Charles and Sylvia Gill", "JerseyNumber": null},
    {"Name": "Kimmy Stein", "Height": "41", "SoccerExperience": "NO", "GuardianName": "Bill and Hillary Stein", "JerseyNumber": null},
    {"Name": "Sammy Adams", "Height": "45", "SoccerExperience": "NO", "GuardianName": "Jeff Adams", "JerseyNumber": null},
    {"Name": "Karl Saygan", "Height": "42", "SoccerExperience": "YES", "GuardianName": "Heather Bledsoe", "JerseyNumber": null},
    {"Name": "Suzane Greenberg", "Height": "44", "SoccerExperience": "YES", "GuardianName": "Henrietta Dumas", "JerseyNumber": null},
    {"Name": "Sal Dali", "Height": "41", "SoccerExperience": "NO", "GuardianName": "Gala Dali", "JerseyNumber": null},
    {"Name": "Joe Kavalier", "Height": "39", "SoccerExperience": "NO", "GuardianName": "Sam and Elaine Kavalier", "JerseyNumber": null},
    {"Name": "Ben Finkelstein", "Height": "44", "SoccerExperience": "NO", "GuardianName": "Aaron and Jill Finkelstein", "JerseyNumber": null},
    {"Name": "Diego Soto", "Height": "41", "SoccerExperience": "YES", "GuardianName": "Robin and Sarika Soto", "JerseyNumber": null},
    {"Name": "Chloe Alaska", "Height": "47", "SoccerExperience": "NO", "GuardianName": "David and Jamie Alaska", "JerseyNumber": null},
    {"Name": "Arnold Willis", "Height": "43", "SoccerExperience": "NO", "GuardianName": "Claire Willis", "JerseyNumber": null},
    {"Name": "Phillip Helm", "Height": "44", "SoccerExperience": "YES", "GuardianName": "Thomas Helm and Eva Jones", "JerseyNumber": null},
    {"Name": "Les Clay", "Height": "42", "SoccerExperience": "YES", "GuardianName": "Wynonna Brown", "JerseyNumber": null},
    {"Name": "Herschel Krustofski", "Height": "45", "SoccerExperience": "YES", "GuardianName": "Hyman and Rachel Krustofski", "JerseyNumber": null}
]
}

restval -

{
 "Players": [
    {"Name": "Name", "Height": "Height (inches)", "SoccerExperience": "Soccer Experience", "GuardianName": "Guardian Name(s)", "JerseyNumber": "13"},
    {"Name": "Joe Smith", "Height": "42", "SoccerExperience": "YES", "GuardianName": "Jim and Jan Smith", "JerseyNumber": "13"},
    {"Name": "Jill Tanner", "Height": "36", "SoccerExperience": "YES", "GuardianName": "Clara Tanner", "JerseyNumber": "13"},
    {"Name": "Bill Bon", "Height": "43", "SoccerExperience": "YES", "GuardianName": "Sara and Jenny Bon", "JerseyNumber": "13"},
    {"Name": "Eva Gordon", "Height": "45", "SoccerExperience": "NO", "GuardianName": "Wendy and Mike Gordon", "JerseyNumber": "13"},
    {"Name": "Matt Gill", "Height": "40", "SoccerExperience": "NO", "GuardianName": "Charles and Sylvia Gill", "JerseyNumber": "13"},
    {"Name": "Kimmy Stein", "Height": "41", "SoccerExperience": "NO", "GuardianName": "Bill and Hillary Stein", "JerseyNumber": "13"},
    {"Name": "Sammy Adams", "Height": "45", "SoccerExperience": "NO", "GuardianName": "Jeff Adams", "JerseyNumber": "13"},
    {"Name": "Karl Saygan", "Height": "42", "SoccerExperience": "YES", "GuardianName": "Heather Bledsoe", "JerseyNumber": "13"},
    {"Name": "Suzane Greenberg", "Height": "44", "SoccerExperience": "YES", "GuardianName": "Henrietta Dumas", "JerseyNumber": "13"},
    {"Name": "Sal Dali", "Height": "41", "SoccerExperience": "NO", "GuardianName": "Gala Dali", "JerseyNumber": "13"},
    {"Name": "Joe Kavalier", "Height": "39", "SoccerExperience": "NO", "GuardianName": "Sam and Elaine Kavalier", "JerseyNumber": "13"},
    {"Name": "Ben Finkelstein", "Height": "44", "SoccerExperience": "NO", "GuardianName": "Aaron and Jill Finkelstein", "JerseyNumber": "13"},
    {"Name": "Diego Soto", "Height": "41", "SoccerExperience": "YES", "GuardianName": "Robin and Sarika Soto", "JerseyNumber": "13"},
    {"Name": "Chloe Alaska", "Height": "47", "SoccerExperience": "NO", "GuardianName": "David and Jamie Alaska", "JerseyNumber": "13"},
    {"Name": "Arnold Willis", "Height": "43", "SoccerExperience": "NO", "GuardianName": "Claire Willis", "JerseyNumber": "13"},
    {"Name": "Phillip Helm", "Height": "44", "SoccerExperience": "YES", "GuardianName": "Thomas Helm and Eva Jones", "JerseyNumber": "13"},
    {"Name": "Les Clay", "Height": "42", "SoccerExperience": "YES", "GuardianName": "Wynonna Brown", "JerseyNumber": "13"},
    {"Name": "Herschel Krustofski", "Height": "45", "SoccerExperience": "YES", "GuardianName": "Hyman and Rachel Krustofski", "JerseyNumber": "13"}
]
}

2 个答案:

答案 0 :(得分:1)

要直接解决您的问题,我认为您应该避免重新考虑。 Restval似乎填补了所有空值。如果玩家的名字是空的,并且你使用了restval,那么玩家的名字最终将是一个2位数字。在我们生活的时代,这可能不是那么奇怪。

我认为你应该循环播放玩家,为每个玩家分配一个JerseyNumber属性值:

import csv
import json
import random

def generate_jersey_number():
    return "".join(random.sample(range(1, 8), 2))

def csv_to_json(csv_file_name_str, json_file_name_str):
    field_names = ["Name", "Height", "SoccerExperience",
                   "GuardianName", "JerseyNumber"]
    # Read the rows of your CSV as dictionaries
    with open(csv_file_name_str, "r") as csv_file:
        reader = csv.DictReader(csv_file, field_names)
        data = {
            'Players': [player for player in reader]
        }
    # Loop over your players, assigning them a jersey number
    for player in data['Players']:
        player['JerseyNumber'] = generate_jersey_number()
    # Dump the entire data structure to JSON
    with open(json_file_name_str, "w") as json_file:
        json.dump(data, json_file)
    return json_file_name_str

您可以在代码中包含的简单改进:

  • 使用with将在退出with块时关闭文件,释放文件句柄。
  • 仅在需要时获取文件句柄,然后将其释放。
  • 不要尝试自己制作JSON字符串。而是使用Python数据结构,然后将它们转储到JSON
  • 全球尝试捕捉既不酷也不好帮。

答案 1 :(得分:0)

所以我能够取得突破:),我创建了一个新功能,在将文件发送到应用程序之前加载文件并添加泽西数字

基本上我从我的Players键获取值(这是一个列表)并循环遍历它,将值添加到给定键并返回一个新的json加载对象。

可能有更有效的方式,但目前我在python中的有限知识只给我一个出路。

def load_json(json_file_name_str):

    try:
        with open(json_file_name_str) as json_file:
            datas = json.load(json_file)
            players = datas["Players"]

            for i in players:
                for key in i:
                    if key=="JerseyNumber":
                        i[key] = "".join(random.sample(JERSEYNUMBERS,2))   
            return datas
    except (TypeError) as e:
        logging.error("Json file loading failed: Caused by -> {}".format(e))