如何合并JSON结果并将properties转为Pandas DataFrame列?
解决方案
你的问题在于直接将properties列转为DataFrame后,每个字段仍是嵌套的字典结构,需要从这些嵌套结构中提取实际值才能得到预期的表格。以下是修正后的代码:
import pandas as pd import json # 读取JSON数据 with open('db.json', encoding='utf-8') as f: data = json.load(f) # 提取所需字段的函数 def extract_properties(props): return { 'ID': props['ID']['rich_text'][0]['text']['content'] if props['ID']['rich_text'] else None, 'Title': props['Title']['title'][0]['text']['content'] if props['Title']['title'] else None, 'Site': props['Site']['rich_text'][0]['text']['content'] if props['Site']['rich_text'] else None, 'Last edited time': props['Last edited time']['last_edited_time'], 'Link': props['Link']['url'], 'Status': props['Status']['select']['name'] if props['Status']['select'] else None } # 处理每个result的properties processed_data = [extract_properties(item['properties']) for item in data['results']] # 转为DataFrame并调整列顺序 df = pd.DataFrame(processed_data)[['Site', 'Last edited time', 'Link', 'Status', 'ID', 'Title']] print(df)
代码说明
- 用
with语句读取文件更安全,避免资源泄漏。 - 定义
extract_properties函数统一处理嵌套字段的提取,同时加入空值判断防止索引报错。 - 遍历
results列表,逐个处理每个对象的properties,整理成结构化数据。 - 最后按你预期的列顺序重新排列DataFrame的列。
运行这段代码后,就能得到你想要的输出格式。
内容的提问来源于stack exchange,提问作者cy614
相关产品推荐
相关产品推荐

