我想用CSV文件中的数据填充我的json消息。我希望每一行都是一个“新的”json对象。我正在使用Python,并且一旦完成就将代码连接到API。有些数据需要归类为“个人信息”和“carinfo”,我需要在下面的“预期的json消息输出”下的正确类别下填充正确的数据。
这是我到目前为止所做的:
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)
我不知道如何添加两个“个人信息”和“carinfo”类别。
示例csv表:
FirstName LastName Age gender Car model Price loan
Anna Andersson 28 F Audi A8 40 FALSE
预期的json消息输出:
{
"personalinfo": {
"firstname": "Anna",
"lastname": "Andersson",
"age": "28",
"gender": "F",
"carinfo": [{
"car": "Audi",
"model": "A8"
}],
"price": 40,
"loan": "FALSE"
}
}
下一条记录应该是一个新的json对象。
答案 0 :(得分:2)
您需要将csv文件中的每一行数据转换为按照您描述的方式布局的JSON对象。这可以通过调用单个函数来完成,该函数从csv文件中获取row
字典并执行此操作:
import csv
import json
def make_record(row):
return {
"personalinfo": {
"firstname": row["FirstName"],
"lastname": row["LastName"],
"age": row["Age"],
"gender": row["gender"],
"carinfo": [{
"car": row["Car"],
"model": row["model"]
}],
"price": row["Price"],
"loan": row["loan"]
}
}
with open('csv_test.csv', 'r', newline='') as csvfile:
reader = csv.DictReader(csvfile, delimiter='\t')
with open('json_file.json', 'w') as jsonfile:
out = json.dumps([make_record(row) for row in reader])
jsonfile.write(out)
# show result
with open('json_file.json', 'r') as jsonfile:
print('results:')
print(json.dumps(json.load(jsonfile), indent=4))