簡體   English   中英

將 json 轉換為格式化字符串

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM