Flask,JSON and content type

Hi guys,

Second question of the day and in a long time. I'm not sure if anyone has any experience with web apps or JSON, nevertheless, no harm in asking. I recently wrote some toy Python code to experiment with Flask. The hello_world() function returns a string or JSON data(I'm not sure which one...). Anyway there are 4 examples of JSON in the hello_world() function, JSON can be a string, a bool, a number, an array or an object(an object can contain more objects).

Here are some examples of valid and invalid JSON

1
2
3
4
5
6
7
8
9
10
11
12
  
  3 // valid(number)
  "hello" // valid(string)
  true // valid (bool)
  [3,"hello"] // valid(array)
  { "number":3, "greeting": "hello" } // valid(object)


  2,3 // invalid(more than one number/need to use array)
  "hello","world" // invalid(more than one string/need to use array)
  { "name": adam, number:3} // invalid(adam has no quotation marks) 


If numbers by themselves(as long as there is just one) are valid json, why does my app/flask not accept it? It seems that Flask will accept an array, a string, a list/array or a object/dictionary.

My final question is.. when expecting the headers of my simple web application the data/content type from my Flask server when I return just string(remember, a single string is valid json) is html/text, but when I return an object/dictionary or list/array, the content type that is sent to the web page is of html/json. Any possible reasons for this?

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@app.route('/')
def hello_world():

    JSON_data = [3] #This is okay!
    #JSON_data = "3" #This is okay too!
    #JSON_data = { number:3 } # Again, this is okay.
    #JSON_data = 3 #For some reason this is not okay!

    return(JSON_data)

# main driver function
if __name__ == '__main__':
    # run() method of Flask class runs the application
    # on the local development server.
	app.run()
I have no experience with Flask but isn't what you have written there just regular Python syntax (which happens to be the same or similar to JSON)?

I think this might explain your second question:
The return value from a view function is automatically converted into a response object for you. If the return value is a string it’s converted into a response object with the string as response body, a 200 OK status code and a text/html mimetype. If the return value is a dict or list, jsonify() is called to produce a response.
https://flask.palletsprojects.com/en/2.2.x/quickstart/#about-responses
Last edited on
I am low experience here but I am unaware of a single element json file as well. In every use case or documentation I have run into, its key:value pairs (and nested variations of that), never just value without a key.
Topic archived. No new replies allowed.