【发布时间】:2020-09-09 09:26:59
【问题描述】:
我想转换这个 json :
{
"rate_limit_by":
[{ "type": "IP",
"extract_from_header": "X-Forwarded-For"
}]
}
到这里:
"{\"rate_limit_by\": [{\"type\": \"IP\", \"extract_from_header\": \"X-Forwarded-For\"}]}".
这样我就可以将其作为 Python 请求中有效负载的一部分发送。
我已经尝试了多种相同的方法。 json.dumps 不起作用,因为在这种情况下它不会转义字符 & .replace(""",r"\"") 不起作用,因为它会创建这样的字符串:
{\\"rate_limit_by\\": [{\\"type\\": \\"IP\\", \\"extract_from_header\\": \\"X-Forwarded-For\\"}]}
(以下是 curl 的示例,但我想使用 python 请求以特定格式发送数据。) 我的上游需要某种格式的数据,截至目前,我正在向上游发送数据,如下所示:
curl -i --request POST --data "rule_name=only_ip" \
--data-binary "@data.txt" \
--url http://localhost:8001/plugin/rules
data.txt 如下所示:
rule={
"rate_limit_by": [
{ "type":"IP", "extract_from_header": "X-Forwarded-For" }
]
}
我正在尝试将其转换为:
curl -i --request POST -H 'Content-Type: application/json' --data-binary @data.json http://localhost:8001/plugin/rules
data.json 应该是这样的
{
"rule_name" : "test_ip",
"rule":"{\"rate_limit_by\": [{\"type\": \"IP\", \"extract_from_header\": \"X-Forwarded-For\"}]}"
}
现在“规则”的值是带有字符转义的字符串。 这是我试图实现并正在使用 python 发布帖子。 以下是相同的代码:-
import requests
import json
import re
url = 'http://localhost:8001/plugin/rules'
rule = {
"rate_limit_by":
[{ "type": "IP",
"extract_from_header": "X-Forwarded-For"
}]
}
rule = json.dumps(json.dumps(rule))
print(rule) #this output the data in correct format
obj = {
"rule_name" : "test_ip",
"rule": rule #but when used it here its get wrapped in two \\
}
headers = {'Content-Type': 'application/json', 'Accept': 'text/plain'}
print(obj)
r = requests.post(url, data=obj, headers=headers)
print(r.text)
【问题讨论】:
-
首先,没有 JSON 对象之类的东西。也许您的意思是 JavaScript 对象的 JSON 表示?其次,JSON 已经是一个字符串了。
-
好的,感谢您的澄清,但我们现在可以解决真正的问题了吗?
-
我不知道,因为我不知道你真正的问题是什么,因为你没有用理解的词解释它。听起来您想将 JSON 转换为字符串 - 但 JSON 已经 是 字符串,因此无需进行转换。
-
@Flimzy 我已经更新了这个问题,你能再看一遍吗?如果您需要更多详细信息,请告诉我。
标签: python json python-3.x nginx lua