You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python从JSON响应生成DataFrame时获取displayName遇KeyError: 'author'问题

Fixing KeyError: 'author' When Building Your DataFrame

Hey there! That KeyError: 'author' is popping up because at least one entry in your json_data['list'] doesn't have an author key — maybe some items don't include author info, or there's a typo in the key name (like Author instead of lowercase author). Let's work through fixes step by step.

First, Diagnose the Problem

Before jumping to code changes, you can quickly spot which entries are missing the author field to confirm:

for idx, item in enumerate(json_data['list']):
    if 'author' not in item:
        print(f"Item {idx} is missing 'author' key: {item.get('contentID', 'no ID')}")

This will show you exactly which content entries are causing the error.

Solution 1: Safely Access Nested Fields with get()

Instead of directly accessing i['author']['displayName'] (which breaks if author doesn't exist), use Python's dict.get() method. It lets you set a default value for missing keys, avoiding errors entirely:

import pandas as pd

# Collect all data in a list first (way more efficient than appending DataFrames repeatedly)
data_rows = []
for item in json_data['list']:
    data_rows.append({
        'Content_id': item['contentID'],
        'subject': item['subject'],
        'published': item['published'],
        'updated': item['updated'],
        'viewCount': item['viewCount'],
        'type': item['type'],
        'name': item.get('author', {}).get('displayName', 'Unknown Author')
    })

# Create the DataFrame in one go
df = pd.DataFrame(data_rows)
  • item.get('author', {}): If author is missing, return an empty dictionary instead of throwing an error.
  • .get('displayName', 'Unknown Author'): If displayName is missing from the author dict, use "Unknown Author" as a placeholder (you can replace this with None if you prefer empty values).

Solution 2: Filter Out Entries Without Author Data

If you don't want to keep entries missing author info, add a check before adding them to your list:

data_rows = []
for item in json_data['list']:
    if 'author' in item and 'displayName' in item['author']:
        data_rows.append({
            'Content_id': item['contentID'],
            'subject': item['subject'],
            'published': item['published'],
            'updated': item['updated'],
            'viewCount': item['viewCount'],
            'type': item['type'],
            'name': item['author']['displayName']
        })
    else:
        # Optional: Log skipped items for debugging
        print(f"Skipping item with missing author data: {item.get('contentID')}")

df = pd.DataFrame(data_rows)

Quick Note: Ditch df.append()

Just a heads-up — pd.DataFrame.append() is deprecated in newer pandas versions. Building a list of dictionaries first and then creating the DataFrame all at once is faster, cleaner, and future-proof.

内容的提问来源于stack exchange,提问作者Mamtha Pillai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:44:05