如何使用嵌套对象将CSV文件转换为特定的JSON格式? [英] How to convert CSV file to a specific JSON format with nested objects?
问题描述
我想用CSV文件中的数据填充json消息.我希望每一行都是一个新" json对象.我正在使用Python,完成后会将代码连接到API.某些数据需要tp归类为"personalinfo"和"carinfo",并且我需要按照下面的"Expected json message output"(正确的json消息输出)在正确的类别下填充正确的数据.
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)
我不知道如何添加两个"personalinfo"和"carinfo"类别.
I do not know how to add the two "personalinfo" and "carinfo" categories.
csv表示例:
FirstName LastName Age gender Car model Price loan
Anna Andersson 28 F Audi A8 40 FALSE
预期的json消息输出:
Expected json message output:
{
"personalinfo": {
"firstname": "Anna",
"lastname": "Andersson",
"age": "28",
"gender": "F",
"carinfo": [{
"car": "Audi",
"model": "A8"
}],
"price": 40,
"loan": "FALSE"
}
}
下一条记录应该是一个新的json对象.
Next record should be a new json object.
推荐答案
您需要将csv文件中的每一行数据转换为您所描述的JSON对象.这可以通过调用单个函数来实现,该函数从csv文件中获取row
字典并执行以下操作:
You need to convert each row of data in the csv file into a JSON object laid-out the way you described. This can be accomplished by calling a single function which takes the row
dictionary from the csv file and does just that:
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))
这篇关于如何使用嵌套对象将CSV文件转换为特定的JSON格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!