[英]Is there a better way to convert a Model to a well formatted JSON string?
[英]Convert json to formatted string
我想转换这个 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)
你的意思是你想以某种方式访问里面的项目吗?
您应该删除“[]”,因为该部分实际上没有意义。
import json
x = str({
"rate_limit_by":
[{ "type": "IP",
"extract_from_header": "X-Forwarded-For"
}]
})
x = x.replace("[","")
x = x.replace("]","")
x = eval(x)
d = json.dumps(x)
l = json.loads(d)
l['rate_limit_by']['type']
这将输出“IP”。 现在你有一本你需要的字典,叫做 l。
desired
的就是你说你需要的东西。json 文件。 以下打印True
。 请参阅https://repl.it/repls/DistantTeemingProtocol 。
import json
desired = r'''{
"rule_name" : "test_ip",
"rule":"{\"rate_limit_by\": [{\"type\": \"IP\", \"extract_from_header\": \"X-Forwarded-For\"}]}"
}'''
d = {
"rate_limit_by": [{
"type": "IP",
"extract_from_header": "X-Forwarded-For"
}]
}
s = json.dumps(d)
xxx = json.dumps({"rule_name": "test_ip", "rule": s}, indent=4)
o = json.loads(desired)
yyy = json.dumps(o, indent=4)
print(xxx == yyy)
如果您要使用请求发布,那么您不应该发布字符串,而应该发布字典。
IE,
r = requests.post(url, json={"rule_name": "test_ip", "rule": s})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.