Flask API does not recognize elif and else conditions

Creating a flask API that deals with various nested JSON files presents an interesting challenge. Depending on the data within these files, different actions need to be taken.

The sorting logic is based on conditional statements as shown below:

if (jsonFile['data']['shape'] == "cube"):
    function(jsonFile)
elif (jsonFile['data']['shape'] == "cone"):
    function(jsonFile)
elif (jsonFile['data']['sphere']):
    function(jsonFile)
else:
    print("Unknown file")

However, when attempting to send a nested JSON file through Postman, like one containing information about a sphere, a

500 error "KeyError: shape"
occurs and bypasses the elif statement entirely.

If I rearrange the order of the elif statements so the one referring to the sphere comes first, only the sphere-related operations work while the others do not. The logic seems to stop at the initial if statement, causing subsequent conditions to be ignored. Even sending random content does not trigger the else statement.

All other statements function correctly on their own.

Example of a JSON file featuring a cube:

{
    "data": {
        "shape": "cube"
    }
}

Example of a JSON file featuring a sphere:

{
    "data": {
        "sphere": {
            "description": "spherical"
        }
    }
} 

The complete error message is as follows:

ERROR in app: Exception on /processshape [POST]
Traceback (most recent call last):
  File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 2525, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 1822, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 1796, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "d:\python\shape-api\app.py", line 34, in processshape
    if (resp['data']['shape'] == "cube"):
KeyError: 'shape'
127.0.0.1 - - [02/Feb/2023 00:03:38] "POST /processshape HTTP/1.1" 500 -

Answer №1

The problem arises when the

if (jsonFile['data']['shape'] == "cube")
statement is executed. This code snippet tries to access the value associated with the key shape within the dictionary jsonFile['data']. However, if the key shape does not exist in the dictionary, a KeyError will be raised and the subsequent elif block will not run.

To resolve this issue, you can modify the code as follows:

if ('shape' in jsonFile['data'] and jsonFile['data']['shape'] == "cube")

This change ensures that you only check the value for the key shape if it actually exists in the dictionary.

A similar modification should be made for other cases as well. If you are not certain that the key data always exists in the jsonFile, you should also verify its presence before accessing it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Develop JSON Object with C# Web Service

Learning the basics of C# Web Services to handle JSON data can be quite challenging. If you have a web service that returns data in JSON format, such as the following example: {"RESULT":"2","TKN":"E952B4C5FA9","URL_HOME":"My_Url_Home"} You may encounter ...

Utilizing the distance-weighted KNN algorithm in the sklearn library

Currently, I am analyzing the UCI eye movement eeg data using KNN. In my implementation, I have set the weights parameter to distance. Below is the code snippet: test_scores = [] train_scores = [] for i in range(1,7): knn = KNeighborsClassifier(i, we ...

Utilize Grunt to retrieve a JSON object from a file

I'm interested in utilizing the grunt-hash plugin to rename my JavaScript files. This plugin generates a new file that contains a map of renamed files: hash: { options: { mapping: 'examples/assets.json', //mapping file so your s ...

What is the method used by numpy to calculate an exponential?

Having recently explored this particular query, I am intrigued by the inner workings of what transpires when invoking np.exp: what precise mathematical or numerical methodology is employed to generate the values within the resulting array? As an illustrati ...

Celery Error: Unable to Receive Emails via Celery

New to Python Django and Celery, I'm looking to set up Celery locally. Right now, my focus is on configuring error emails for failed tasks. Here's what I've done so far: Added the following code to setting.py CELERY_SEND_TASK_ERROR_EMAILS ...

I am facing difficulties in adding dynamic content to my JSON file

I've encountered a challenge in appending new dynamic data to a JSON file. In my project, I receive the projectName from an input form on the /new page. My API utilizes node.js's fs module to generate a new JSON file, where I can subsequently add ...

Is there a way to retrieve the initial value from the second element within the JSON data?

Exploring JSON Data Collections In my JSON data, I have two collections: FailedCount and SucceededCount. { "FailedCount": [{ "FailedCount_DATE_CURRENT_CHECK": "2016-11-30 10:40:09.0", "FailedCount_DATE__CURRENT__CHECK": "10:40:09", "FailedCo ...

Struggling with Python version selection when creating egg files in Eclipse for Python development

My current setup involves using CentOS with Python 2.6 (/usr/bin/python2.6), but I have also installed Python 2.7.8 (/usr/local/lib/python2.7). However, when running a script in Eclipse, the egg files are being created in /usr/bin/python2.6/.. instead of ...

Having trouble retrieving documents on a Windows 8.1 mobile device

For my app, I am utilizing Json files as a means of local storage. Interestingly, when using Visual Studio's emulator, reading and writing to the files function properly. However, upon connecting an actual device and attempting to run the app on it, I ...

Generating a generic list in C# using JArray

Currently, I am facing a challenge with my dynamic import process that involves converting Json into an object array. My main obstacle lies in creating a List<> based on a string reference to the class object. To elaborate, I am retrieving json data from ...

Python code to create a table from a string input

Suppose I have a table like this: greeting = ["hello","world"] Then, I convert it into a string: greetingstring = str(greeting) Now the challenge is to change it back into a table. What would be the approach for accomplishing this tas ...

Querying a JSON field in BigQuery yields empty results

Once more, I am struggling with my SQL query on a JSON field in bigquery. This JSON data can be found at this link - The specific record I am working with has an id of 1675816490 Here is the SQL statement I am using: SELECT ##JSON_EXTRACT(jso ...

Parse the local JSON file and convert it into an array that conforms to an

My goal is to extract data from a local JSON file and store it in an array of InputData type objects. The JSON contains multiple entries, each following the structure of InputData. I attempted to achieve this with the code snippet below. The issue arises ...

Encountering an 'undefined' error while attempting to showcase predefined JSON data on an HTML webpage

As I try to display the predefined JSON data from https://www.reddit.com/r/science.json on an HTML page, I keep encountering the message "undefined." Below is a snippet of my HTML code: $.getJSON('https://www.reddit.com/r/science.json', funct ...

Dynamic Data Visualization using ChartJS with MySQL and PHP

I'm trying to create a line chart using chartJs that will display MySQL data. Specifically, I would like to use PHP to push the MySQL data to the chartJs. Here is an example of the MySQL table: id | page_views | visitors | month | ---------------- ...

I have a json file that I need to convert to a csv format

I am currently working with a json file, but I need to switch it out for a csv file. Do I have to use a specific library to accomplish this task, or can I simply modify the jQuery 'get' request from json to csv? I attempted the latter approach, b ...

Multithreading in Python does not function properly in Visual Studio

I'm currently working on a project involving the multiprocessing library. However, when I try to run my code in Visual Studio on my Windows PC, it seems to get stuck and nothing is being printed. Here's the snippet of code that's causing me ...

What is the best way to access the global variables within a module's namespace?

Is there a method to retrieve the dictionary that stores the global variables within a specific module namespace? It seems possible if the module includes at least one function as follows: import mymodule d = mymodule.func.__globals__ Is this accurate? ...

Transmitting JSON data using a Jquery AJAX request in PHP

I'm facing an issue passing a JSON array from a jQuery AJAX call to a PHP file and attempting to write the received data to a file. This is my code: var contacts = [{"address":[],"phone":[],"last_name":"abc","email":[{"address":"<a href="/cdn-cgi/ ...

Tips for showing the parsed JSON data in a TableView using a TextField

Hello there, I am just starting out with iPhone development and need some guidance. I'm currently working on incorporating a webservice to fetch JSON response strings, parsing them using JSONvalue and displaying the parsed data on labels through butt ...