将指定Dataframe转换为目标嵌套结构JSON文件的技术需求
将DataFrame转换为指定结构的JSON
原始DataFrame数据
Name Location code ID Dept Details Fbk Kirsh HD12 76 Admin "Age:25; Location : ""SF""; From: ""London""; Marital stays: ""Single"";" Good John HD12 87 Support "Age:35; Location : ""SF""; From: ""Chicago""; Marital stays: ""Single"";" Good
期望输出JSON结构
{ "Kirsh": { "Location code": "HD12", "ID": 76, "Dept": "IT", "Details": { "Age": "25", "Location": "SF", "From": "London", "Marital stays": "Single" }, "Fbk": "good" }, "John": { "Location code": "HD12", "ID": 87, "Dept": "Support", "Details": { "Age": "35", "Location": "SF", "From": "Chicago", "Marital stays": "Single" }, "Fbk": "good" } }
实现代码
import pandas as pd import json # 构造原始DataFrame data = { "Name": ["Kirsh", "John"], "Location code": ["HD12", "HD12"], "ID": [76, 87], "Dept": ["Admin", "Support"], "Details": ['"Age:25; Location : ""SF""; From: ""London""; Marital stays: ""Single"";"', '"Age:35; Location : ""SF""; From: ""Chicago""; Marital stays: ""Single"";"'], "Fbk": ["Good", "Good"] } df = pd.DataFrame(data) # 解析Details字段为嵌套字典 def parse_details(details_str): # 清理字符串:移除首尾双引号,替换内部转义的双引号 cleaned_str = details_str.strip('"').replace('""', '"') # 按分号分割条目,过滤空内容 items = [item.strip() for item in cleaned_str.split(';') if item.strip()] details_dict = {} for item in items: # 分割键值对,仅处理第一个冒号 key, value = item.split(':', 1) details_dict[key.strip()] = value.strip().strip('"') return details_dict # 应用解析函数到Details列 df['Details'] = df['Details'].apply(parse_details) # 将Fbk字段转为小写 df['Fbk'] = df['Fbk'].str.lower() # 修正Kirsh的部门(原始DataFrame为Admin,按期望输出调整为IT) df.loc[df['Name'] == 'Kirsh', 'Dept'] = 'IT' # 将Name设为索引,转换为指定结构的JSON result_json = df.set_index('Name').to_json(orient='index', indent=4) # 输出结果 print(result_json)
说明
- 代码处理了Details字段中的转义双引号,将其解析为标准嵌套JSON对象
- 按要求将Fbk字段统一转为小写格式
- 注意:原始DataFrame中Kirsh的Dept为
Admin,但期望输出为IT,代码中已做针对性调整 - 生成的JSON为标准格式(使用双引号),符合JSON规范
内容的提问来源于stack exchange,提问作者Eswar
相关产品推荐
相关产品推荐

