You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用FastAPI搜索JSON文件时遭遇JSONDecodeError问题求助

JSONDecodeError 问题排查与解决

错误根源

  • 文件指针耗尽:你在函数外部提前打开了文件read = open('sample.json'),第一次请求执行json.load(read)后,文件指针会移动到文件末尾。后续再调用这个接口时,json.load(read)读取的是空内容,直接触发Expecting value的解码错误。
  • JSON结构与代码逻辑不匹配:你的JSON是单个对象({...}),但代码里用for i in data遍历,这会遍历对象的键名(如"id"、"name"),而非你预期的对象元素,逻辑本身就不成立。

修复代码

from fastapi import FastAPI
import json

app = FastAPI()

@app.get("/key/{hole}", status_code=200)
def fetch_message(*, hole: int): 
    # 每次请求重新打开文件,用with自动管理文件资源
    with open('sample.json', 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    # 直接匹配单个对象的id
    if data['id'] == hole:
        return data['message']
    
    # 处理id不匹配的情况
    return {"detail": "指定ID不存在"}

扩展场景优化(如果JSON是数组格式)

如果后续你的JSON文件改为多个对象的数组(比如[{"id":0,...}, {"id":1,...}]),可以调整为遍历逻辑:

@app.get("/key/{hole}", status_code=200)
def fetch_message(*, hole: int): 
    with open('sample.json', 'r', encoding='utf-8') as f:
        data_list = json.load(f)
    
    for item in data_list:
        if item['id'] == hole:
            return item['message']
    
    return {"detail": "指定ID不存在"}

内容的提问来源于stack exchange,提问作者Boros

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 21:30:56