File size: 1,271 Bytes
1c980b1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import json
import sys
def show_jsonl_object(file_path, index=0):
"""
从JSONL文件中提取并展示指定索引位置的对象
:param file_path: JSONL文件路径
:param index: 要提取的对象索引(从0开始)
"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
for i, line in enumerate(f):
if i == index:
try:
data = json.loads(line)
print(f"第 {index} 个对象的JSON内容:")
print(json.dumps(data, indent=4, ensure_ascii=False))
return
except json.JSONDecodeError:
print(f"错误:第 {index} 行不是有效的JSON格式")
return
print(f"警告:文件只有 {i+1} 行,无法读取第 {index} 行")
except FileNotFoundError:
print(f"错误:文件 {file_path} 不存在")
if __name__ == "__main__":
if len(sys.argv) < 2:
print("使用方法:python show_jsonl.py <文件路径> [行号]")
sys.exit(1)
file_path = sys.argv[1]
index = int(sys.argv[2]) if len(sys.argv) > 2 else 0
show_jsonl_object(file_path, index) |