简体   繁体   中英

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"} ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM