2

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?

1 Answer 1

5

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

6 Comments

I have tried what you've suggested, but now I get the following error: TypeError: 'NoneType' object is not subscriptable
That implies that you're not actually getting any JSON to your endpoint then. It's hard to see from your code snippet but you'd need to check how questionObj0 is defined
I see what you mean, but when I use print(question) in Python, it does print out the object that I have sent from JavaScript, it's just when I try to access it using question['question'], it gives me the NoneType error
I'm not sure how that can be possible; that suggests that "question" is simultaneously None and not None, which obviously can't be the case. Is there any other code that we're not seeing that could be the cause?
I found the issue :) I think I was trying to send an object which didn't exist yet, it only existed once I pressed a submit button, which calls a function to create the objects. I edited my Python to this: @app.route('/test', methods=['GET', 'POST']) def test(): if request.method == 'POST': question = request.get_json() print(question['question']) return render_template('test.html') if request.method == 'GET': return render_template('test.html')
|

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.