Mario
Mario

Reputation: 3445

Submitting a http post via python and seeing escape characters in the json posted

I am posting via python (totally new language for me so I am sure I am overlooking something basic) and seeing escape characters in the json posted to the server which obviously results in invalid json. Here is my code:

import requests
#try three different ways to escape json - all result in the backslash being submitted to the server in the post
json = """{"testId": "616fdb5e-40c1-326a-81a4-433051627e6d","testName": "nameHere"}"""    
#json = '{"testId": "616fdb5e-40c1-326a-81a4-433051627e6d","testName": "nameHere"}'   
#json = "{\"testId\": \"616fdb5e-40c1-326a-81a4-433051627e6d\",\"testName\": \"nameHere\"}"
response = requests.post("http://localhost:8888", data=None, json=json)

I am posting locally to fiddler and see that the escape characters are still there. Here is what is posted:

"{\"testId\": \"616fdb5e-40c1-326a-81a4-433051627e6d\",\"testName\": \"nameHere\"}"

I would expect the library to strip out escape characters. Is that not the case?

The other weird thing is that the characters aren't there when I am running the code, at least from what I can tell:

json
'{"testId": "616fdb5e-40c1-326a-81a4-433051627e6d","testName": "nameHere"}'
json.find("\\")
-1

Upvotes: 1

Views: 1149

Answers (1)

Mario
Mario

Reputation: 3445

Short answer is don't submit a string, the response method wants a dict. Code that works:

import requests
json_dict = {"testId": "616fdb5e-40c1-326a-81a4-433051627e6d","testName": "nameHere"}
response = requests.post("http://localhost:8888", data=None, json=json_dict)

Upvotes: 4

Related Questions