如何将含LinkedIn信息的JSON字典内容写入Excel并格式化
解决方案
我们可以用pandas库高效处理数据结构并写入Excel,以下是完整实现步骤:
1. 依赖安装
先确保安装必要的库:
pip install pandas openpyxl
(openpyxl是pandas写入xlsx格式文件的依赖)
2. 代码实现
import pandas as pd import json # 测试用字典(如果从JSON文件读取,替换为下面的注释代码) data_dict = { 'https://www.linkedin.com/in/manashi-sherawat-mathur-phd-3a97b69': { 'showallexperiences': [ {'company_url': 'https://www.linkedin.com/company/1612/'}, {'company_url': 'https://www.linkedin.com/search/results/all/?keywords=Independent+Pharma%2FBiotech+Professional'} ], 'showalleducation': [ {'university_url': 'https://www.linkedin.com/company/3555/'}, {'university_url': None} ] }, 'https://www.linkedin.com/in/baneshwar-singh-6143082b/': { 'showallexperiences': [ {'company_url': 'https://www.linkedin.com/company/166810/'}, {'company_url': 'https://www.linkedin.com/company/166810/'} ], 'showalleducation': [ {'university_url': 'https://www.linkedin.com/company/6737/'}, {'university_url': 'https://www.linkedin.com/company/5826549/'} ] } } # 从JSON文件读取数据的代码(替换上面的测试字典) # with open('your_data.json', 'r', encoding='utf-8') as f: # data_dict = json.load(f) # 整理数据为行格式 rows = [] for linkedin_url, details in data_dict.items(): row = {'LinkedIn URL': linkedin_url} # 处理公司URL,生成带编号的列 experiences = details.get('showallexperiences', []) for idx, exp in enumerate(experiences, start=1): col_name = f'Company {idx}' row[col_name] = exp.get('company_url', '') # 将None转为空字符串 # 处理大学URL,生成带编号的列 educations = details.get('showalleducation', []) for idx, edu in enumerate(educations, start=1): col_name = f'University {idx}' row[col_name] = edu.get('university_url', '') rows.append(row) # 转换为DataFrame并写入Excel df = pd.DataFrame(rows) df.to_excel('linkedin_data.xlsx', index=False, engine='openpyxl') print("数据已成功写入linkedin_data.xlsx")
代码说明
- 遍历每个LinkedIn主URL,将对应的公司、大学URL分别映射到
Company 1、Company 2、University 1等带编号的列 - 自动处理
None值,转为Excel中的空单元格 - 支持从JSON文件读取原始数据(取消注释对应的读取代码即可)
- 最终Excel文件中,每个LinkedIn URL单独占一行,所有关联的公司、大学URL按编号列展示
内容的提问来源于stack exchange,提问作者Julieta M.
相关产品推荐
相关产品推荐

