如何将含逗号分隔字段的DataFrame转换为指定嵌套JSON?
解决方法:将DataFrame的Sections字段转为数组后导出JSON
要实现目标JSON格式,核心是先把DataFrame中Sections列的字符串值转换为列表(数组)类型,再导出JSON即可。
步骤1:转换Sections字段为列表
使用Pandas的str.split()方法,按字符串中的, 分隔符拆分字段值,将其转为列表:
df['Sections'] = df['Sections'].str.split(', ')
如果SQL返回的Sections字符串存在分隔符前后空格不一致的情况(比如"4700A1/305,4700A1/312"),可以用更鲁棒的写法处理:
df['Sections'] = df['Sections'].str.split(',').apply(lambda x: [item.strip() for item in x])
步骤2:导出为指定格式的JSON
处理完字段类型后,再用to_json()导出,参数保持orient='records'和indent=2即可:
json_result = df.to_json(orient='records', indent=2)
完整示例代码
import pandas as pd # 模拟从SQL获取的DataFrame df = pd.DataFrame({ 'Survey': "001_220816080015", 'BCD': "001_220816080015.bcd", 'Sections': "4700A1/305, 4700A1/312" }) # 转换Sections为列表 df['Sections'] = df['Sections'].str.split(', ') # 导出JSON print(df.to_json(orient='records', indent=2))
运行后输出的JSON格式将完全符合你的需求:
[ { "Survey": "001_220816080015", "BCD": "001_220816080015.bcd", "Sections": [ "4700A1/305", "4700A1/312" ] } ]
内容的提问来源于stack exchange,提问作者Roy Jaques
相关产品推荐
相关产品推荐

