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

使用Python调用LinkedIn API时如何解决JSONDecodeError?

LinkedIn API调用出现JSONDecodeError:Expecting value的解决方法

问题描述

已成功获取LinkedIn访问令牌并实例化LinkedInApplication对象,但调用任何方法时抛出JSONDecodeError,相关代码如下:

# Set up LinkedIn API credentials and scope
LINKEDIN_CLIENT_ID = "myappclientid"
LINKEDIN_CLIENT_SECRET = "myappclientsecret"
REDIRECT_URI = 'https://localhost:8000'
SCOPE = ['r_emailaddress', 'r_liteprofile', 'w_member_social']

# Create LinkedInAuthentication object with credentials and scope
authentication = linkedin.LinkedInAuthentication(
                    LINKEDIN_CLIENT_ID,
                    LINKEDIN_CLIENT_SECRET,
                    REDIRECT_URI,
                    SCOPE
                )

# Get the authorization URL to prompt user to grant access
authorization_url = authentication.authorization_url
print(authorization_url)

# User should visit the URL and be redirected to a localhost URL with a 'code' parameter
response_url = input("Please enter the redirected URL:")
parsed_url = urlparse(response_url)
query_params = parse_qs(parsed_url.query)
code_param = query_params.get('code', [None])[0]

# Set authorization code in the authentication object to retrieve access token
authentication.authorization_code = code_param
access_token = authentication.get_access_token()
print("Access token:", access_token[0])

# Create LinkedInApplication object with access token
application = linkedin.LinkedInApplication(token=access_token[0])

# Try to get the user's profile with the LinkedInApplication object
try:
    application.get_profile()
except Exception as e:
    print("Error: ", e)

错误栈片段:

Traceback (most recent call last):   File
"/usr/local/lib/python3.10/site-packages/requests/models.py", line
971, in json
    return complexjson.loads(self.text, **kwargs)   File "/usr/local/Cellar/python@3.10/3.10.11/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/__init__.py",
line 346, in loads
    return _default_decoder.decode(s)   File "/usr/local/Cellar/python@3.10/3.10.11/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/decoder.py",
line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())   File "/usr/local/Cellar/python@3.10/3.10.11/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/decoder.py",
line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None 
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char
0)
 
During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File
"/usr/local/lib/python3.10/site-packages/linkedin/utils.py", line 56,
in raise_for_error

原因分析

你使用的linkedin库是针对LinkedIn v1 API开发的,但LinkedIn已于2019年彻底废弃v1 API,当前仅支持v2 API。老库调用已下线的v1端点时,LinkedIn会返回非JSON格式的响应(比如404错误页的HTML内容),导致JSON解析失败,抛出JSONDecodeError。

另外,你申请的权限(r_emailaddress、r_liteprofile等)均为v2 API专属权限,老库无法适配这些权限对应的v2端点调用逻辑。

修复方案

方案1:直接用requests调用LinkedIn v2 API

放弃老的linkedin库,用requests直接构造v2 API请求,示例代码如下:

import requests

# 替换为你的实际访问令牌
ACCESS_TOKEN = "your_access_token_here"

# 获取用户基础信息(需r_liteprofile权限)
def get_lite_profile():
    url = "https://api.linkedin.com/v2/me"
    headers = {
        "Authorization": f"Bearer {ACCESS_TOKEN}",
        "Content-Type": "application/json"
    }
    response = requests.get(url, headers=headers)
    response.raise_for_status()  # 主动抛出HTTP错误
    return response.json()

# 获取用户邮箱(需r_emailaddress权限)
def get_user_email():
    url = "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))"
    headers = {
        "Authorization": f"Bearer {ACCESS_TOKEN}",
        "Content-Type": "application/json"
    }
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    return response.json()

# 调用示例
try:
    profile = get_lite_profile()
    print("用户基础信息:", profile)
    email_data = get_user_email()
    print("用户邮箱:", email_data['elements'][0]['handle~']['emailAddress'])
except Exception as e:
    print("错误:", e)

方案2:使用支持v2 API的第三方库

使用专门适配LinkedIn v2 API的库,比如python-linkedin-v2(先执行pip install python-linkedin-v2安装),示例代码如下:

from linkedin_v2 import linkedin

# 初始化客户端
client = linkedin.LinkedInClient(access_token="your_access_token_here")

# 获取用户基础信息
profile = client.get_profile()
print(profile)

# 获取用户邮箱
email = client.get_email_address()
print(email)

关键注意事项

  • 确认LinkedIn开发者后台中,你的应用已启用对应v2 API权限,且申请的scope与调用的API端点匹配。
  • 访问令牌必须包含目标API所需的权限,否则会返回权限不足的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 03:07:47