Exicode
Exicode

Reputation: 53

Error when using JSON to send Javascript object to Python Flask

I am using ajax to POST a JSON string to Python Flask but get the following error:

Error

This is my JavaScript:

$.ajax({
type: 'POST',
url: window.location.href,
data: JSON.stringify(questionObj0),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
}).done(function(msg) {
  console.log(msg);
});

And this is my Python:

@app.route('/test', methods=['GET', 'POST'])
def test():
    question = request.get_json()
    question1 = json.loads(question)
    print (question)
    return render_template('test.html')

Using print(question) yields the following output (same output when tested in JavaScript using browsers console):

{'questionNumber': 1, 'question': 'Convert 10110001 to decimal', 'answer': 177, 'userAnswer': 'blank'}

From what I understand, the output should be a string and therefore padded with quotation marks.

Has anyone come across anything similar/know how to fix the issue?

Upvotes: 2

Views: 1368

Answers (1)

Matt Healy
Matt Healy

Reputation: 18531

Flask's request.get_json() returns a dict object from the JSON data supplied in the request, so you don't need to call json.loads on it again.

app.py

@app.route('/', methods=['GET'])                                                
def index():                                                                    
    return render_template('index.html')                                        


@app.route('/test', methods=['POST'])                                           
def test():                                                                     
    question = request.get_json()                                               
    print(question['question'])                                                 
    return ''

templates/index.html

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>

var questionObj0 = {'questionNumber': 1, 'question': 'Convert 10110001 to decimal', 'answer': 177, 'userAnswer': 'blank'};

console.log(JSON.stringify(questionObj0));

$.ajax({
    type: 'POST',
    url: '{{ url_for('test') }}',
    data: JSON.stringify(questionObj0),
    dataType: 'json',
    contentType: 'application/json; charset=utf-8'
}).done(function(msg) {
    console.log(msg);
});

</script>

Upvotes: 5

Related Questions