SoFunction
Updated on 2025-03-03

Solution to get published JSON objects in Python Flask App

A simple web application was developed on Python framework Flask, trying to get a JSON response from a POST AJAX request. Here is the code for AJAX calls:

var hotel=$( "#listHotel option:selected" ).val();
$.ajax({
    url: "/getHotels",
    contentType: "application/xml; charset=utf-8",
    data: ({'hotel':hotel}),
    type: "POST",
    success: function(response){
        var r= (response);
        var rating =
        alert(rating);
        $("#rate").html("Ratings : "+rating);
        $("#rate").show('slow');
        (response);
    },
    error: function(error){
        alert(response);
        (error);
    }
});

In Python code, it looks like this:

def getHotels():
    try:
        _hotel = {"value": ['hotel']}
        print _hotel
        hotel= _hotel["value"]
        print hotel

But not obtainedJSONObject,Request help to obtainJSONObject/value。

Solution

In order to get published JSON objects in a Python Flask application, you can follow these steps:

  • Use the request.get_json() method to get the JSON data in the request body.
  • Load JSON data into a dictionary.
  • Access key-value pairs of JSON data from a dictionary.

The following sample code demonstrates how to get a published JSON object and get data from it:

from flask import Flask, request

app = Flask(__name__)

@('/get_json', methods=['POST'])
def get_json():
    json_data = request.get_json()  # Get JSON data in the request body    data = (json_data)  # Load JSON data into a dictionary
    # Access key-value pairs of JSON data from dictionary    hotel = data['hotel']
    rating = data['rating']

    # Return response    return {'hotel': hotel, 'rating': rating}

if __name__ == '__main__':
    ()

In the above code,request.get_json()Method is used to obtain JSON data in the request body and store the result injson_datain variable. Then, use()Method loads JSON data into a dictionary and stores it indatain variable. Finally, fromdataKey-value pairs to access JSON data in the dictionary.

  1. Make sure you have it installed in the Flask applicationflask-restfullibrary.
  2. Import in Flask applicationflask_restfullibrary.
  3. Create an API resource class to handle JSON requests.
  4. Define a method to handle POST requests in the API resource class.
  5. In the method of processing POST requests, userequest.get_json()Methods to obtain JSON data in the request body.
  6. Load JSON data into a dictionary.
  7. Access key-value pairs of JSON data from a dictionary.

The following sample code demonstrates how to use itflask-restfulThe library gets the published JSON object and gets the data from it:

from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class Hotel(Resource):
    def post(self):
        json_data = request.get_json()  # Get JSON data in the request body        data = (json_data)  # Load JSON data into a dictionary
        # Access key-value pairs of JSON data from dictionary        hotel = data['hotel']
        rating = data['rating']

        # Return response        return {'hotel': hotel, 'rating': rating}

api.add_resource(Hotel, '/hotel')

if __name__ == '__main__':
    ()

In the above code, the flask-restful library is first imported. Then, an API resource class Hotel is created in the Flask application and a method that handles POST requests is defined. In the post() method, the request.get_json() method is used to obtain the JSON data in the request body and store the result in the json_data variable. Then, use the() method to load the JSON data into a dictionary and store it in a data variable. Finally, access the key-value pairs of JSON data from the data dictionary.

The above is the detailed content of the solution to obtain published JSON objects in Python Flask App. For more information about obtaining JSON objects in Python Flask App, please follow my other related articles!