Work with JSON



   {JSON} is a standard text format, which is used by REST API for data interchange. For more information on what is JSON click here.

In Previous section, we return a normal string to our client, but now to meet with REST API criteria we going to return a json text.

base on the previous code we need to add this thing;

1. A flask library to manipulate json file

from flask import jsonify

2. a method that return json and where can it be called by client


@app.route('/helloJson')
def hello_Json():
    jsonData = {
        "field1_str":"value1",
        "field2_boolean": True,
        "field3_json":
            {
                "f3_field1_str":"subJson"
            }
    }
    return jsonify(jsonData)

here we can define jsonData as a Dictionary and let's jsonify convert it json format.
in fact json fomat is really similar to Dictionary with and addition of header and some minority thing.

each item consist of two thing:

  • key - always a string
  • value - can be lots of various string, integer, array, or another json!  

and we done!

here's the complete code;


from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/')
def hello_world():
    return "hello world"

@app.route('/helloJson')
def hello_Json():
    jsonData = {
        "field1_str":"value1",
        "field2_boolean": True,
        "field3_json":
            {
                "f3_field1_str":"subJson"
            }
    }
    return jsonify(jsonData)

if __name__ =="__main__":
    app.run()

So, if you access from the homepage it will return same string "Helloworld" to access the new method you need to access though "localhost:5000/helloJson"

below is the result at my browser ( I use Chrome browser and also install plugin app for json viewer)



Deemarc Burakitbumrung

A software develper who graduated from Electronic and Communication Engineer. Have an interest in the field of programming and embedded system.

No comments:

Post a Comment