从CSV转换后如何组织JSON输出?

时间:2019-07-03 19:14:30

标签: python arrays json csv

我正在尝试将csv文件转换为json文件以发送到api。我在创建的json输出的结构上遇到困难。

import csv
import json

csvfile = open('User_List.csv', 'r')
jsonfile = open('user_list.json', 'w')    

csv_reader = csv.DictReader(csvfile)
for row in reader:
    json.dump(row, jsonfile, indent = 4)
    jsonfile.write('\n')

我的代码当前输出:

{
    "firstName": "Richard",
    "lastName": "Tyler",
    "email": "hallbeth@placeholder.email",
    "zip": "58570"
}

我需要阅读:

{
    "email": "hallbeth@placeholder.email",
    "Datafields": {"firstName": "Richard",
                   "lastName": "Tyler",
                   "zip": "58570"}
}

3 个答案:

答案 0 :(得分:0)

我们将此称为temp_dict

temp_dict = {
    "firstName": "Richard",
    "lastName": "Tyler",
    "email": "hallbeth@placeholder.email",
    "zip": "58570"
}

new_dict = {
    "email" : temp_dict["email"],
    "Datafields" : { 
        "firstName": temp_dict["firstName"],
        "lastName": temp_dict["lastName"],    
        "zip": temp_dict["zip"]        
        }

您可以简单地创建一个新字典并以这种方式为其键分配值

答案 1 :(得分:0)

您可以根据原始的data做出格言,并对"DataFields"进行理解:

{'email': data['email'], 'Datafields' : {k:v for k,v in data.items() if k!='email'}}

请参见下面的示例

data =  data = {
    "firstName": "Richard",
    "lastName": "Tyler",
    "email": "hallbeth@placeholder.email",
    "zip": "58570"
}
organized = {
    'email': data.get('email'),
    'Datafields' : {k:v for k,v in data.items() if k!='email'}
}
print(organized)
{'email': 'hallbeth@placeholder.email', 'Datafields': {'firstName': 'Richard', 'lastName': 'Tyler', 'zip': '58570'}}

答案 2 :(得分:0)

您需要重新整理每一行中的数据,使其具有所需的格式,然后再以JSON格式输出:

import csv
import json

with open('User_List.csv', 'r', newline='') as csvfile, \
     open('user_list.json', 'w') as jsonfile:

    for row in csv.DictReader(csvfile):
        # Reorganize data into desired format.
        restructured = {
            'email': row['email'],
            'Datafields':
              {fieldname: value for (fieldname, value) in row.items()
                  if fieldname != 'email'}
        }
        json.dump(restructured, jsonfile, indent=4)
        jsonfile.write('\n')