How To Read And Display JSON using Python


In this tutorial, you’ll learn how to read and display JSON using Python. Let’s use Flask Python web framework and see how to read and display JSON data while reading from an API.

Start by creating a project folder called python-app. Install Flask and Requests using pip. Requests library will be used for making the API call.

    pip insall flask
    pip install requests

Create a file called hello.py inside python-app folder and add the following code :

    from flask import Flask
    from flask import jsonify
    import requests
    app = Flask(__name__)
    api_url = "https://jsonplaceholder.typicode.com/todos/1"
    
    @app.route("/getJsonData")
    def get_json_data():
        try:
          api_response = requests.get(api_url)
          json_dict = api_response.json()
          return jsonify(json_dict)
        except Exception as e:
          print("Error occured :: %s" % e.message)

As seen in the above code, requests returns JSON data from the API. .json method converts the raw data response to dictionary. Using jsonify you return the JSON content from the Python flask endpoint.

So, this is how you read and display JSON while working with APIs in Python Flask.