json.decoder.JSONDecodeError: extra data: line 1 column 2 (char 1)
这个错误信息表明在尝试解析JSON数据时,遇到了额外的、未被预期的数据。这通常发生在尝试将一个包含多个JSON对象的字符串作为一个单独的JSON对象来解析时。
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。JSON数据通常是由键值对组成的,可以表示对象、数组、数字、字符串、布尔值或null。
这个错误通常发生在以下情况:
确保你尝试解析的字符串只包含一个完整的JSON对象。例如:
import json
json_str = '{"name": "Alice", "age": 30}'
data = json.loads(json_str)
如果你确实有一个包含多个JSON对象的字符串,你需要逐个解析它们。可以使用循环和json.JSONDecoder
来实现:
import json
def parse_multiple_json(json_str):
decoder = json.JSONDecoder()
pos = 0
while pos < len(json_str):
try:
obj, pos = decoder.raw_decode(json_str, pos)
yield obj
except json.JSONDecodeError as e:
print(f"Error decoding JSON at position {e.pos}: {e}")
break
json_str = '{"name": "Alice", "age": 30}{"name": "Bob", "age": 25}'
for obj in parse_multiple_json(json_str):
print(obj)
使用在线JSON验证工具(如jsonlint.com)来检查你的JSON字符串是否格式正确。
假设你有一个包含多个JSON对象的文件data.json
:
{"name": "Alice", "age": 30}
{"name": "Bob", "age": 25}
你可以这样读取和解析:
import json
def parse_json_file(file_path):
with open(file_path, 'r') as file:
decoder = json.JSONDecoder()
pos = 0
while True:
line = file.readline()
if not line:
break
try:
obj, pos = decoder.raw_decode(line, pos)
yield obj
except json.JSONDecodeError as e:
print(f"Error decoding JSON at position {e.pos}: {e}")
for person in parse_json_file('data.json'):
print(person)
通过这些方法,你可以有效地处理和解析JSON数据,避免JSONDecodeError
错误。