-1

I am sending the array of dicts from javascript to python via a POST request that looks this way:

mydata.push({
            department_id: department_id,
            cardgroup_id: cardgroup,
            doorgroup_id: doorgroup
        });


$.post("data/save-office/"+office, {'data': JSON.stringify(mydata)}, function (data) {
        console.log(data);
        });


When extracting the payload in python:

    departments = request.form.getlist('data')

The output is:

departments = ['[{"department_id":"1","cardgroup_id":"2","doorgroup_id":"2550"},
{"department_id":"2","cardgroup_id":"2","doorgroup_id":"2550"},
{"department_id":"3","cardgroup_id":"2","doorgroup_id":"2550"},
{"department_id":"4","cardgroup_id":"2","doorgroup_id":"2550"}]']

This displayed output is an array of one index and the inside is treated as a string rather than a dictionary.

How can I filter it or send it from javascript so that it can be decoded as an array of dicts not an array of strings?

julien.giband
  • 2,467
  • 1
  • 12
  • 19
Omar Abdelrazik
  • 683
  • 2
  • 9
  • 30
  • There are a number of libraries for parsing JSON; you can probably guess what some of their names are. – Scott Hunter Mar 30 '22 at 15:54
  • Does this answer your question? [How to parse data in JSON format?](https://stackoverflow.com/questions/7771011/how-to-parse-data-in-json-format) – solarissmoke Apr 25 '22 at 12:25

1 Answers1

0

Without changing your code, the simplest solution is using the json library's load or loads (load safe) method

import json
departments_string = request.form.getlist('data')[0]
departments = json.loads(departments_string)
print(departments)

[{'department_id': '1', 'cardgroup_id': '2', 'doorgroup_id': '2550'}, {'department_id': '2', 'cardgroup_id': '2', 'doorgroup_id': '2550'}, {'department_id': '3', 'cardgroup_id': '2', 'doorgroup_id': '2550'}, {'department_id': '4', 'cardgroup_id': '2', 'doorgroup_id': '2550'}]

I would further question using getlist, but we would need more deatils from you to deal with that.

Chillie
  • 1,356
  • 13
  • 16