0

I passed ajax data to my route using:

$.ajax({
    type:"POST",
    url: "/process",
    data: {json:self.json, filename:self.documentName},
    success: function(){
        console.log("Success");
    },
    error: function(){
        console.log("Error");
    }
}).done(function(){
    console.log("Finished");
});

and I have my route handler:

@app.route("/process", methods=['POST'])
def process():
    if request.method == 'POST':
        data = request.form.to_dict()
        print data
        filename = data['filename']
        # v-- this line doesnt work. --v
        jsonData = data['json']
        return data

and the print returned:

{'filename': u'', 'json[install_ide]': u'true', 'json[username]': u'_currently_not_used_', 'json[password]': u'_currently_not_used_', 'json[install_git]': u'true', 'json[clear_cache]': u'true', 'json[ide_install_directory]': u'', 'json[dart_install_directory]': u'', 'json[repo_list][]': u'seg_ui','json[default_install_path]': u'C:\\code\\', 'json[code_directory]': u'', 'json[fresh_repo_pull]': u'true', 'json[install_dart]': u'true', 'json[git_url]': u'', 'json[abs_repo_path][]': u'', 'json[git_install_directory]': u''}

It could not use the following:

data["json"]["install_ide"]

I opened up a python terminal and applied the data, and just as expected I couldn't use that syntax.

How would I take this complex data object and properly process it so I could use that syntax.

Liran Funaro
  • 2,750
  • 2
  • 22
  • 33
Fallenreaper
  • 10,222
  • 12
  • 66
  • 129

1 Answers1

3

Use the following syntax instead to parse the data:

data = request.get_json(force=True)

This will keep the original structure of the JSON object.

The request.form.to_dict() meant to parse forms data, which is never supposed to be nested.

Liran Funaro
  • 2,750
  • 2
  • 22
  • 33