0

I have JSON data stored in a variable in [{"totalspend": 3240.650785131, "dailybudget": 50.0}] format.

I am trying to post this JSON data to a url using:

import requests
r = requests.post("myurl", myjson)

but I am not able to see the result on my url after executing the code.

1
  • What, does it contain a literal Python list? What does print(repr(myjson)) show (please include the quotes that produces). Commented Jan 31, 2014 at 9:24

2 Answers 2

2

Your server most likely expects the Content-Type: application/json header to be set:

r = requests.post("myurl", data=myjson, 
                  headers={'Content-Type': 'application/json'})

Do make sure that myjson is an actual JSON string and not a Python list.

If you are using requests version 2.4.2 or newer, you can leave the encoding of the JSON data entirely to the library; it'll set the correct Content-Type header for you automatically. You'd pass in the Python object (not a JSON string) to the json keyword argument:

 r = requests.post("myurl", data=myobject)
Sign up to request clarification or add additional context in comments.

Comments

0

You need to set headers first : Try :

import json
import requests
payload = {"totalspend": 3240.650785131, "dailybudget": 50.0}
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), headers=headers)

Comments