1

I have a response created with jsonify and I need to add additional data in that response. Is this possible?

I have:

from flask import make_response, jsonify
resp = make_response(jsonify({"data": {"person": {"name": "ko", "error": "not responding"}}}), 500)
...

I need to do something like:

resp.append(jsonify({"value":1}))

So I can return both data and value in the same json.

2
  • Can't you just make 1 more complex JSON? I believe HTTP requests only allow 1 response... Commented Jun 23, 2017 at 8:40
  • 3
    Why don't you insert the value to the data dict before you make response? Commented Jun 23, 2017 at 8:40

2 Answers 2

1

I'd suggest working with the data before making the response. Before jsonify is called on the data, it is simply a normal python dictionary object, and you can work with it as you please:

data = {"data": {"person": {"name": "ko", "error": "not responding"}}}

data['value'] = 1
# and any other processing here

make_response(jsonify(data), 500)

Edit: looking at the flask Response object docs it doesn't look like it really wants you editing it once you have made the response. However if you really need to edit the response object after creating it, the flask docs here would be a good place to start.

Sign up to request clarification or add additional context in comments.

Comments

1

As it has already been said it's better not to modify the response object. Prepare the data, then jsonify it and return the response. However, you can still modify the response:

import json from flask import make_response, jsonify

resp = make_response(jsonify({"data": {"person": {"name": "ko", "error": "not responding"}}}), 500)
data = json.loads(response.get_data())
# If you use python3 then add decode('utf-8') at the end.
# data = json.loads(response.get_data().decode('utf-8'))
data['value'] = 1
resp.set_data(json.dumps(data))
return resp

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.