JSON decode error when trying search through JSON file via FAST Api

Question:

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!"
}
Asked By: Boros

||

Answers:

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!"
    }
]
Answered By: Amos Baker

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
Answered By: Bastien B
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.