简体   繁体   中英

How do I organize JSON output after converting from CSV?

I'm trying to convert a csv file to a json file to send to an api. I'm having difficulty with structure of the json output that I've created.

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')

My code currently outputs:

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

and I need it to read:

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

Let's call this 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"]        
        }

You can simply create a new dictionary and assign values to it's key in this manner

You could make a dict from your original data and use a comprehension for "DataFields" :

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

See below for example

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'}}

You need to reorganize the data from each row so it's in the format you want before outputting it in JSON format:

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM