简体   繁体   English

Python:Json转储转义引用

[英]Python: Json dumps escape quote

There is a POST request which works perfectly when I pass the data as below: 当我传递数据时,有一个POST请求可以正常工作,如下所示:

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'} . 但是当我在字典上使用json.dumps()并发送响应时,我没有得到响应(响应代码504),使用headers={'Content-Type': 'application/json'} Have also tried json parameter of Post requests. 还试过了Post请求的json参数。

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\\"}"数据不一样。

json.dumps({"styleId":"BMHSUR2HTS"}) == "{\\"styleId\\":\\"BMHSUR2HTS\\"}" gives False even though a print on both shows a similar string. json.dumps({"styleId":"BMHSUR2HTS"}) == "{\\"styleId\\":\\"BMHSUR2HTS\\"}"给出False即使两者上的打印显示相似的字符串。

How can I get the same format as "{\\"styleId\\":\\"BMHSUR2HTS\\"}" from a dictionary {"styleId":"BMHSUR2HTS"} ? 如何从字典{"styleId":"BMHSUR2HTS"}获得与"{\\"styleId\\":\\"BMHSUR2HTS\\"}"相同的格式?

If you print the json.dumps({"styleId":"BMHSUR2HTS"}) , you will notice two things: 如果你打印json.dumps({"styleId":"BMHSUR2HTS"}) ,你会发现两件事:

  1. your output is a string (just try type(json.dumps({"styleId":"BMHSUR2HTS"})) ); 你的输出是一个字符串(只是尝试type(json.dumps({"styleId":"BMHSUR2HTS"})) );
  2. if you pay attention the output will add a space between the json name and value: {"styleId": "BMHSURT2HTS"} . 如果注意,输出将在json名称和值之间添加一个空格: {"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(': ', ':') 替换json.dumps输出上的空格: json.dumps({"styleId":"BMHSUR2HTS"}).replace(': ', ':')
  2. Convert all to json by using eval(): eval(json.dumps({"styleId":"BMHSUR2HTS"})) and eval(YOUR_JSON_STRING) 使用eval()将all转换为json: eval(json.dumps({"styleId":"BMHSUR2HTS"}))eval(YOUR_JSON_STRING)

I hope this helps you. 我希望这可以帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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