如何创建从csv到json的嵌套字段?我看了另一个stackoverflow,但是它们不是我想要格式化的。我有一个数据集,有一列,我必须转换成一个嵌套字段。你知道吗
数据:
ID, NAME
1, "Smith, Mr. Adams"
2, "McAdams, Mrs. Audrey"
3, "McAdams, Doctor John"
4, "Missing Value"
代码:
with open('test.csv', 'r') as file:
headers = next(file) #skip the headers
fieldnames = headers.rstrip().split(",")
csv_reader = csv.DictReader(file, fieldnames) #creating a dictionary
import datetime
for row_dict in csv_reader:
row_dict['name'] = row_dict['name'].split(",")
json_data = json.dumps(row_dict)
print(json_data)
我正在列表中获取输出,但它不是嵌套的。你知道吗
{"id": "1", "name": ["Smith", " Mr. Adams"]}
{"id": "2", "name": ["McAdams", " Mrs. Audrey"]}
{"id": "3", "name": ["McAdams", " Doctor John"]}
{"id": "4", "name": ["Missing Value"]}
最终输出:有什么方法可以做到这一点吗?你知道吗
{"id": "1", "name": [{"last_name": "Smith",
"prefix": "Mr.",
"first_name": "Adams"}]}
{"id": "1", "name": [{"last_name": "McAdams",
"prefix": "Mrs.",
"first_name": "Audrey"}]}
{"id": "1", "name": [{"last_name": "McAdams",
"prefix": "Dr.",
"first_name": "John"}]}
{"id": "1", "name": [{"last_name": "Missing Value",
"prefix": "Missing Value",
"first_name": "Missing Value"}]}
只需多次使用
.split()
,然后创建一个新的dict输出:
只需多次使用
.split()
,然后创建一个新的dict输出:
相关问题 更多 >
编程相关推荐