将 json 转换为格式化字符串

我想将此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\"}]}"
    }

现在"rule"的值是带有字符转义的字符串。 我尝试使用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) #这会以正确的格式输出数据

obj = {
        "rule_name" : "test_ip",
        "rule": rule #但是当在这里使用它时,它会被包装在两个\\中
    }
headers = {'Content-Type': 'application/json', 'Accept': 'text/plain'}

print(obj)

r = requests.post(url, data=obj, headers=headers)

print(r.text)
点赞
用户11693768
用户11693768

你的意思是你想以某种方式访问里面的项目吗?

你应该去掉“[]”,因为那部分没有什么意义。

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 的你所需要的字典。

2020-05-22 14:09:43
用户88888888
用户88888888

desired 是你在 something.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)

如果你想使用 requests 进行 POST 请求,那么你应该使用字典而不是字符串进行 POST。

例如,

r = requests.post(url, json={"rule_name": "test_ip", "rule": s})
2020-05-22 14:22:46