0

Am new to flask+jinja2 and am trying to post json data to my server from jinja2 template and store the json data in db.

However when I use the following code in my jinja2 html and post, I cant seem to read it as json data and flask is reading it as string and truncating the data. please help.

myhtml.html:

<form action= "/v1/json_data" method="post">
    <!-- some code -->
    {% set json_data =  process_data()  %}
    <input type="hidden" name="json_data" value={{ json_data|safe }}>
    <input type="submit" name="form_data" value="Submit">
</form>

views.py:

@app.route('/v1/json_data', methods=['POST'])
def read_json_data():
    if request.method == 'POST':
        form_data = request.form["some_id_i_defined_in_html"]
        json_data = request.form.get('json_data', None)
        print(form_data) # works as expected :)
        print(json_data) # only prints first key as string :(
        return json_data

My json_data is of the following format:

{"level1a": {"level2a": "2a", "level2aa": "2aa"},
"level1b": {"level2b": "2b", "level2bb": "2bb"}}

The json_data print statement in views.py only prints

{"level1a":

and I expect entire json structure. What am I missing here? TIA

1 Answer 1

1

You have to call flask.request.json to return a JSON object decoded from the request. This question is similar to: How to get POSTed JSON in Flask?

    json_data = flask.request.json
    a_value = json_data["a_key"]
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.