I want to populate my json message with data from a CSV file. I want each row to be a "new" json object. I am using Python and will connect the the code to an API once done. Some of the data needs tp be categorized under "personalinfo" and "carinfo" and I need the correct data to be populated under the right category as under the "Expected json message output" below.
This is what I have so far:
import csv
import json
csvfile = open('test.csv', 'r')
jsonfile = open('file.json', 'w')
fieldnames = ("firstname","r", "lastname","r", "age","r", "gender","r",
"model","r", "price","r", "loan","r")
reader = csv.DictReader(csvfile, fieldnames)
out = json.dumps( [ row for >row in reader ] )
jsonfile.write(out)
I do not know how to add the two "personalinfo" and "carinfo" categories.
Example csv table:
FirstName LastName Age gender Car model Price loan
Anna Andersson 28 F Audi A8 40 FALSE
Expected json message output:
{
"personalinfo": {
"firstname": "Anna",
"lastname": "Andersson",
"age": "28",
"gender": "F",
"carinfo": [{
"car": "Audi",
"model": "A8"
}],
"price": 40,
"loan": "FALSE"
}
}
Next record should be a new json object.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…