Vaulstein
Vaulstein

Reputation: 22041

Python: Json dumps escape quote

There is a POST request which works perfectly when I pass the data as below:

url = 'https://www.nnnow.com/api/product/details'

requests.post(url, data="{\"styleId\":\"BMHSUR2HTS\"}", headers=headers)

But when I use json.dumps() on a dictionary and send the response, I do not get the response (response code 504), using headers={'Content-Type': 'application/json'} . Have also tried json parameter of Post requests.

requests.post(url, data=json.dumps({"styleId":"BMHSUR2HTS"}), headers={'content-type': 'application/json'})

Now, the data returned by json.dumps({"styleId":"BMHSUR2HTS"}) and "{\"styleId\":\"BMHSUR2HTS\"}" is not the same.

json.dumps({"styleId":"BMHSUR2HTS"}) == "{\"styleId\":\"BMHSUR2HTS\"}" gives False even though a print on both shows a similar string.

How can I get the same format as "{\"styleId\":\"BMHSUR2HTS\"}" from a dictionary {"styleId":"BMHSUR2HTS"} ?

Upvotes: 2

Views: 5218

Answers (1)

Fabricio
Fabricio

Reputation: 76

If you print the json.dumps({"styleId":"BMHSUR2HTS"}), you will notice two things:

  1. your output is a string (just try type(json.dumps({"styleId":"BMHSUR2HTS"})));
  2. if you pay attention the output will add a space between the json name and value: {"styleId": "BMHSURT2HTS"}.

Not sure how do you want to handle this, and in your entry code, but there are 2 main options to workaround this issue:

  1. Replace the space on json.dumps output: json.dumps({"styleId":"BMHSUR2HTS"}).replace(': ', ':')
  2. Convert all to json by using eval(): eval(json.dumps({"styleId":"BMHSUR2HTS"})) and eval(YOUR_JSON_STRING)

I hope this helps you.

Upvotes: 2

Related Questions