Prem
Prem

Reputation: 652

How to get a JSON Object in Python (Flask Framework)

How to get a JSON Object in Python (Flask Framework). Below is my code snippet `

var hotel=$( "#listHotel option:selected" ).val();      
        if(hotel!="select")
        {       
        $.ajax({
            url: '/getHotels',
            data: {'hotel':hotel},          
            type: 'POST',
            success: function(response){
                alert(response);
                var r= JSON.parse(response);                
                var rating =r.message               
                $("#rate").html("Ratings : "+rating);
                $("#rate").show('slow');                
                console.log(response);
            },
            error: function(error){
                alert(response);
                console.log(error);
              }
          });
        }`

How can I get the JSON value hotel in my Python script Flask Framework

from flask import Flask, render_template, json, request
app = Flask(__name__)

@app.route('/')
def main():
    return render_template('index.html')
@app.route('/getHotels',methods=['POST','GET'])
def getHotels():     
    try:        
        _hotel=request.POST['hotel']
        print _hotel

this is my code in Python

Upvotes: 0

Views: 2274

Answers (1)

doru
doru

Reputation: 9110

In your javascript transform the data to JSON and set the contentType to "application/json":

data: JSON.stringify({'hotel':hotel}),
contentType : "application/json",

In your flask function get the JSON using request.json:

@app.route('/getHotels')
def getHotels():
    hotel = request.json['hotel']
    .....

Upvotes: 4

Related Questions