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

从Crunchbase爬取的JSON文件中无法找到contact_fields字段排查

问题分析:从Crunchbase爬取的JSON中提取contact_fields失败

问题详情

我有一个从Crunchbase爬取的JSON文件,想要从中提取并打印contact_fields字段,该字段的示例格式如下:

"contact_fields": {
              "contact_email": "info@email.com",
              "phone_number": "+44 800 011 9688"
            },

我编写了如下Python代码来提取联系邮箱和电话号码:

import json  # 注:原代码缺失该导入语句,需补充

with open('html_found.json') as filter:
    data = json.load(filter)

# Find and print the specified content if it exists
if "contact_fields" in data:
    contact_fields = data["contact_fields"]
    contact_email = contact_fields.get("contact_email")
    phone_number = contact_fields.get("phone_number")

    if contact_email:
        print("Contact Email:", contact_email)
    else:
        print("Contact Email not found.")

    if phone_number:
        print("Phone Number:", phone_number)
    else:
        print("Phone Number not found.")
else:
    print("No contact fields found in the JSON data.")

运行代码后输出No contact fields found in the json,但contact_fields字段确实存在于JSON文件中,请问是文件本身存在错误还是代码有问题?

原因排查与解决方案

核心原因

你的代码直接在JSON的顶层数据对象中查找contact_fields,但该字段大概率嵌套在某个子层级(比如organization或其他对象)下,并非顶层键,所以代码找不到它。

解决步骤

  1. 先确认字段层级:
    运行以下代码打印JSON的完整结构,定位contact_fields的具体位置:

    import json
    
    with open('html_found.json') as f:
        data = json.load(f)
        # 打印顶层所有键,快速查看结构
        print("顶层键列表:", list(data.keys()))
        # 打印格式化后的完整数据,方便定位层级
        print(json.dumps(data, indent=2, ensure_ascii=False))
    
  2. 调整代码层级访问:
    根据打印结果,修改代码的访问路径。比如如果contact_fields在data["organization"]下,代码应改为:

    import json
    
    with open('html_found.json') as f:
        data = json.load(f)
    
    # 按实际层级访问contact_fields
    target_data = data.get("organization")  # 替换为实际的父级键
    if target_data and "contact_fields" in target_data:
        contact_fields = target_data["contact_fields"]
        print("Contact Email:", contact_fields.get("contact_email") or "未找到")
        print("Phone Number:", contact_fields.get("phone_number") or "未找到")
    else:
        print("未找到contact_fields字段。")
    
  3. 额外检查项:

    • 确认原代码补充了import json语句(原代码缺失该导入,运行会报错);
    • 检查文件路径,确保html_found.json是你要读取的目标文件,没有读错同名文件;
    • 验证JSON文件语法:如果json.load()没有抛出异常,说明文件语法没问题,无需担心格式错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 15:23:14