0

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

3
  • You are not sending JSON, so there is no JSON for Flask to get. Commented Jul 16, 2015 at 7:57
  • did u try anything in flask...if you do..then would you mind to show them here? Commented Jul 16, 2015 at 7:57
  • Now I eited my question with the Python Code in Flask Commented Jul 16, 2015 at 8:31

1 Answer 1

4

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']
    .....
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.