Home > database >  JSON decode error when trying search through JSON file via FAST Api
JSON decode error when trying search through JSON file via FAST Api

Time:10-01

raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

is the error I am getting when I run the following code:

read = open('sample.json')
@app.get("/key/{hole}", status_code=200)
def fetch_message(*, hole: int): 
    data = json.load(read)
    for i in data:
     if i['id'] == hole:
        return(i['message'])
        break

My json file looks something like this:

{
    "id": 0,
    "name": "John Doe",
    "message": "Hello World!"
}

CodePudding user response:

You are attempting to iterate through the keys of the single entry in your json data. I believe what you want is to iterate through a list of entries of json data so your sample.json should be like this instead:

[
    {
        "id": 0,
        "name": "John Doe",
        "message": "Hello World!"
    }
]

CodePudding user response:

You are tring to iterate over json, clearly that couldn't go well.

This version work with a file containing 1 json object, like yours.

read = open('sample.json')
@app.get("/key/{hole}", status_code=200)
def fetch_message(*, hole: int): 
    data = json.load(read)
    if data['id'] == hole:
        return(data['message'])
        break  # this is not reacheable
  • Related