首页 > 解决方案 > 从列表json.decoder.JSONDecodeError循环时出现python错误:期望值:第1行第1列(char 0)

问题描述

我正在制作一个脚本,用来自 api 的响应填充文本文档。该 api 被要求将用户名从列表转换为通用唯一标识符。我不断收到此错误,无法找到解决方法。“json.decoder.JSONDecodeError:预期值:第 1 行第 1 列(字符 0)”

account.txt 示例

knapplace
Coppinator
tynow
Pman59
ButterMusty
FlyHighGuy13
Seyashi
fluzzygirl1
SquidMan55
leonrules9
BarthGimble
MTR_30
Darkshadow402
Deathmyster
Team_Everlook
Sheathok
KCFrost
mendog
Allfaal117
theLP25D
Zimyx
Blurrnis
redboy678
moose_breeder
kaser12345
import requests
import json

file1 = open('accounts.txt', 'r')

usernames = []

for line in file1:

    stripped_line = line.strip()
    usernames.append(stripped_line)

file1.close()

for x in usernames:

    username = str(x)

    url = ("https://api.mojang.com/users/profiles/minecraft/"+username+"?at=1462770000")

    y = requests.get(url)
    y_data = y.json()
    uuid = y_data['id']

    uuids = []
    uuids.append(uuid)

    file2 = open('uuids.txt', 'w')
    file2.writelines(uuids)
    file2.close()

    file2 = open('uuids.txt', 'r')
    lines = file2.readlines()

标签: pythonjsonpython-3.xlistpython-requests

解决方案


我检查了您粘贴的网址。如果用户不存在,API 不会返回任何内容,但仍会返回成功状态。这就是错误的意思——它期望有一个 JSON 对象以char 0.

y.json()本质上,在尝试通过检查执行 a 之前,您需要处理响应为空的情况y.content。如果y.content为空,则跳过处理当前用户名并转到下一个。

y = requests.get(url)
if len(y.content) == 0:
   continue  # Skip processing this username

# The rest of the code only runs if y.content is not empty.
y_data = y.json()
uuid = y_data['id']

推荐阅读