python - 从列表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()
解决方案
我检查了您粘贴的网址。如果用户不存在,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']
推荐阅读
- c++ - 在 C++ 中有没有办法用流和输出文件开始一个新行?
- apache-spark - Spark - 使用 JSON 文件的许可模式将所有记录移动到损坏的列
- java - 什么是 Android 中的 MediaCodec、MediaExtractor 和 MediaMuxer?
- mysql - Django 无法连接到 mysql
- python - 为什么我的锁定频道命令不起作用???不和谐.py
- angularjs - AngularJS - 将 HTTP 和自定义 Promise 与递归混合
- python - 这个的时间复杂度是多少?我认为它是 O(n) 但不是吗?
- r - ggplot2中的两面板散点图
- assembly - NASM YASM 添加数组的数字
- label - 在 Nativescript 中,有没有办法将 wordwrap 连接标签?