I am still a newbie with Python and working on my first REST API. I have a JSON file that has a few levels. When I create the data frame with pandas, no matter what I try I cannot access the level I need.
The API is built with Flask and has the correct parameters for the book, chapter and verse.
Below is a small example of the JSON data.
{
"book": "Python",
"chapters": [
{
"chapter": "1",
"verses": [
{
"verse": "1",
"text": "Testing"
},
{
"verse": "2",
"text": "Testing 2"
}
]
}
]
}
Here is my code:
@app.route("/api/v1/<book>/<chapter>/<verse>/")
def api(book, chapter, verse):
book = book.replace(" ", "").title()
df = pd.read_json(f"Python/{book}.json")
filt = (df['chapters']['chapter'] == chapter) & (df['chapters']['verses']['verse'] == verse)
text = df.loc[filt].to_json()
result_dictionary = {'Book': book, 'Chapter': chapter, "Verse": verse, "Text": text}
return result_dictionary
Here is the error I am getting:
KeyError
KeyError: 'chapter'
I have tried normalizing the data, using df.loc to filter and just trying to access the data directly.
Expecting that the API endpoint will allow the user to supply the book, chapter and verse as arguments and then it returns the text for the given position based on those parameters supplied.
3
Answers
You are trying to access a list in a dict with a dict key ?
filt = (df[‘chapters’][0][‘chapter’] == "chapter") & (df[‘chapters’][0][‘verses’][0][‘verse’] == "verse")
Will get a result.
But df.loc[filt] requires a list with (boolean) filters and above only gerenerates one false or true, so you can’t filter with that.
You can filter like:
You can first create a dataframe of the JSON and then query it.
Here
df
would look like this afterjson_normalize
:And
result
is:One of the issues here is that
"chapters"
is a listThis is why
["chapters"]["chapter"]
wont work as you intend.If you’re new to this, it may be helpful to "normalize" the data yourself:
It is possible to pass this to
pd.DataFrame()
Although it’s not clear if you need a dataframe here at all.