将json转换为格式化的字符串

时间:2020-05-22 13:59:45

标签: python json python-3.x nginx lua

我要转换此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) #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)

2 个答案:

答案 0 :(得分:0)

您是说要以某种方式访问​​其中的项目吗?

您应该删除“ []”,因为该部分实际上没有意义。

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。

答案 1 :(得分:0)

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)

如果要使用请求进行POST,则不应发布字符串,而应发布字典。

r = requests.post(url, json={"rule_name": "test_ip", "rule": s})
相关问题