Python 官方文档:入门教程 => 点击学习
目录尝试解析空字符串会导致错误错误的常见原因尝试解析无效的 JSON 值忘记用引号括起属性或字符串值对属性或值使用单引号而不是双引号确保你没有尾随逗号发出 Http 请求时得到空响应
python“json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) ”发生在我们试图解析一些无效的 JSON 时。
要解决该错误,请确保响应或文件不为空,或者在解析之前有条件地检查内容类型。
这是一个非常简单的示例,说明错误是如何发生的。
import json
# ⛔️ json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
result = json.loads('')
我们试图将一个空字符串当作有效的 JSON 来解析。
最常见的错误原因是:
下面是一个存储无效 JSON 的文件示例。
example.json
{
"id": 1,
'name': "Alice",
"age": 30,
"country": "Austria"
}
请注意
,名称属性用单引号引起来。
这会使 JSON 无效,并且尝试从文件中读取会导致错误。
import json
file_name = 'example.json'
# ⛔️ json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 3 column 3 (char 15)
with open(file_name, 'r', encoding='utf-8') as f:
my_data = json.load(f)
print(my_data)
要解决该错误,需要确保将 JSON 中的所有键和字符串值用双引号引起来。
example.json
{
"id": 1,
"name": "Alice",
"age": 30,
"country": "Austria"
}
现在 name 键用双引号括起来,我们可以安全地从文件中读取。
# ✅ works as expected
import json
file_name = 'example.json'
with open(file_name, 'r', encoding='utf-8') as f:
my_data = json.load(f)
# ?️ {'id': 1, 'name': 'Alice', 'age': 30, 'country': 'Austria'}
print(my_data)
print(my_data['name']) # ?️ Alice
确保在打开文件时设置编码关键字参数(如上面的代码示例所示)。
以下是无效和有效 JSON 值的一些示例。
example.json
// ⛔️ 无效的 JSON(忘记引用属性)
{
"name": "Alice",
age: 30
}
对象中的 age 属性未用双引号引起来,这使得 JSON 无效。
example.json
// ✅ 有效的 JSON(所有属性都用双引号引起来)
{
"name": "Alice",
"age": 30
}
示例中的 JSON 是有效的,因为所有属性和字符串值都用双引号引起来。
确保没有属性或字符串值用单引号引起来。
example.json
// ⛔️ 无效的 JSON(用单引号引起来的名称属性)
{
'name': "Alice",
"age": 30
}
示例中的名称属性用单引号引起来,这使得 JSON 无效。
永远不要在 JSON 中使用单引号。 属性名称和字符串值必须用双引号引起来。
example.json
// ✅ 有效的 JSON(属性名称和值用双引号引起来)
{
"name": "Alice",
"age": 30
}
在数组的最后一个元素或最后一个键值对之后有尾随逗号会使我们的 JSON 无效。
example.json
// ⛔️ 无效的 JSON(最后一个属性后的尾随逗号)
{
"name": "Alice",
"age": 30, ?️ 这个逗号使它无效 JSON
}
请注意
,在 age 属性之后有一个尾随逗号。
这会使 JSON 无效,因为不允许使用尾随逗号。
要解决该错误,请确保删除所有结尾的逗号。
example.json
// ✅ 有效的 JSON(没有尾随逗号)
{
"name": "Alice",
"age": 30
}
如果我们在发出 API 请求时遇到错误,请确保响应在解析之前具有 application/json
内容类型标头。
import requests
def make_request():
response = requests.delete('https://example.com/api/users/2')
print('response: ?️', response) # response: ?️ <Response [204]>
print('response.text: ?️', response.text) # response.text: ?️ ""
# response.status_code: ?️ 204
print('response.status_code: ?️', response.status_code)
print('response.headers: ?️', response.headers)
if (response.status_code != 204
and 'content-type' in response.headers
and 'application/json' in response.headers['content-type']):
parsed = response.json()
print('✅ parsed response: ?️', parsed)
else:
# ?️ this runs
print('⛔️ conditions not met')
make_request()
该示例使用 requests
包并发出 HTTP DELETE
请求,该请求返回 204 状态(无内容)。
尝试像解析 JSON 一样解析空响应会引发 JSONDecodeError
,因此我们必须检查:
application/json
。这样我们就可以确定服务器在尝试使用 reponse.json()
方法(如果使用请求)或 json.loads(my_json_str)
解析它之前向我们发送了一个有效的 JSON 响应。
如果服务器向我们发送了一个空响应或响应不是 application/json
类型,我们将收到 JSONDecodeError
。
我们不能尝试像解析 JSON 一样解析 text/html
或 XML 响应(或空响应)。
该错误通常是在以下情况下引起的:
我们可以使用 json.load()
方法将 JSON 文件反序列化为 Python 对象。
import json
file_name = 'example.json'
with open(file_name, 'r', encoding='utf-8') as f:
my_data = json.load(f) # ?️ 使用 load() 解析 JSON
print(my_data) # ?️ {'name': 'Alice', 'age': 30}
该示例假定在同一目录中有一个名为 example.json 的文件。
example.json
{"name": "Alice", "age": 30}
确保我们正在读取的文件不为空,因为这通常会导致错误。
如果我们的文件可能包含无效的 JSON,请使用 try/except
语句来处理错误。
假设我们有以下 JSON 文件。
example.json
{
"name": "Alice",
'age': 30
}
请注意,age 属性是单引号的,这使得 JSON 无效。
下面是我们如何使用 try/except
语句来处理错误。
import json
file_name = 'example.json'
with open(file_name, 'r', encoding='utf-8') as f:
try:
my_data = json.load(f) # ?️ 使用 load() 解析 JSON
print(my_data)
except BaseException as e:
print('The file contains invalid JSON')
我们尝试从文件中解析 JSON 数据,但文件包含无效的 JSON,因此引发异常,然后在 except 块中处理。
错误的另一个常见原因是在尝试从 JSON 文件读取时将文件路径传递给 json.loads()
方法。
import json
file_name = 'example.json'
with open(file_name, 'r', encoding='utf-8') as f:
# ⛔️ json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
my_data = json.loads(file_name) # ?️ incorrectly passed file path
print(my_data) # ?️ {'name': 'Alice', 'age': 30}
json.load
方法用于将文件反序列化为 Python 对象,而 json.loads
方法用于将 JSON 字符串反序列化为 Python 对象。
import json
file_name = 'example.json'
with open(file_name, 'r', encoding='utf-8') as f:
my_data = json.load(f) # ✅ 将文件对象传递给 json.load()
print(my_data) # ?️ {'name': 'Alice', 'age': 30}
json.load()
方法需要一个包含实现.read()
方法的 JSON 文档的文本文件或二进制文件。
或者,我们可以手动调用文件对象的 read()
方法并使用 json.loads()
方法。
import json
file_name = 'example.json'
with open(file_name, 'r', encoding='utf-8') as f:
# ?️ 确保调用 read()
my_data = json.loads(f.read())
print(my_data) # ?️ {'name': 'Alice', 'age': 30}
print(type(my_data)) # ?️ <class 'dict'>
上面的示例实现了相同的结果,但是我们没有依赖 json.load() 方法为我们调用文件对象上的 read() ,而是手动执行它并使用 json.loads() 方法。
json.loads()
方法基本上帮助我们从 JSON 字符串加载 Python 本机对象(例如字典或列表)。
如果我们需要在使用 json.loads()
方法之前使您的 JSON 有效,我们可以尝试使用 str.replace()
方法。
下面是一个示例 JSON 文件,其中包含使 JSON 无效的单引号属性。
example.json
{
"name": "Alice",
'age': 30
}
下面是我们如何使用 str.replace()
方法将字符串中的单引号替换为双引号。
import json
file_name = 'example.json'
with open(file_name, 'r', encoding='utf-8', errors='ignore') as f:
a_str = f.read()
# {
# "name": "Alice",
# 'age': 30 ?️ note single quotes
# }
print(a_str)
# ✅ 用双引号替换单引号
valid_json = a_str.replace("'", '"')
result = json.loads(valid_json)
print(result) # {'name': 'Alice', 'age': 30}
print(result['name']) # Alice
print(result['age']) # 30
str.replace
方法返回字符串的副本,其中所有出现的子字符串都被提供的替换项替换。
该方法采用以下参数:
我们使用 replace()
方法将字符串中所有出现的单引号替换为双引号。
这使得 JSON 有效,因此我们可以安全地使用 json.loads()
方法。
JSONEncoder 类默认支持以下对象和类型的转换。
Python | JSON |
---|---|
Python | JSON |
dict | object |
list, tuple | array |
str | string |
int、float、int 和 float 派生枚举 | number |
True | true |
False | false |
None | null |
最常见的错误原因是:
Python“json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) ”发生在我们试图解析一些无效的 JSON 时。
要解决该错误,需要确保响应或文件不为空或在解析前有条件地检查内容类型。
到此这篇关于Python 中JSONDecodeError: Expecting value: line 1 column 1 (char 0)错误的文章就介绍到这了,更多相关Python JSONDecodeError内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: 解决Python中JSONDecodeError:Expectingvalue:line1column1(char0)错误
本文链接: https://www.lsjlt.com/news/200881.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0