Search code examples
pythonarraysjsonflaskflask-restful

RESTful-Flask parsing JSON Arrays with parse_args()


This's my code:

parser = reqparse.RequestParser(bundle_errors=True)    
parser.add_argument('list', type=list, location="json")

class Example(Resource):
    def post(self):
        #json_data = request.get_json(force=True)
        json_data = parser.parse_args()
        return json_data

If I post a JSON object like this:

{
  "list" : ["ele1", "ele2", "ele3"]
}

parser.parse_args() parses it to this python list:

'list': ['e','l','e','1']

request.get_json() works, but I would really like to have the validation of the reqparser... How can I get the parser.parse_args() working properly with JSON arrays?

(I get this error: TypeError("'int' object is not iterable",) is not JSON serializable, if if the JSON array contains integers: 'list': [1, 2, 3])


Solution

  • chuong nguyen is right in his comment to your question. With an example:

    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('options', action='append')
        parser = parser.parse_args()
        options = parser['options']
    
        response = {'options': options}
        return jsonify(response)
    

    With this, if you request:

    curl -H 'Content-type: application/json' -X POST -d '{"options": ["option_1", "option_2"]}' http://127.0.0.1:8080/my-endpoint
    

    The response would be:

    {
        "options": [
          "option_1",
          "option_2"
        ]
    }