【问题标题】:Convert json to formatted string将json转换为格式化字符串
【发布时间】: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


【解决方案1】:

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})

【讨论】:

  • 嘿,这么棒的 hack,所以当我打印它时这似乎有效,但是当将它传递给某个键的值时,它再次给出 \\ 斜线。请看下面的代码。 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 这失败了。 -----
  • 对不起,我无法在评论中格式化我的代码:(,这是我关于堆栈溢出的第一个问题。
  • 那么,如果您以后要使用字典,为什么还需要 JSON 字符串呢?为什么不直接使用原版字典?
  • 这个\是把\转义,这样你就可以看到了
  • 它因为我无法按原样发送字典,我需要将其格式化为特定格式。请查找我作为示例给出的具体格式。做任何其他方式来实现我在本节中解释的上述格式:- [data.json 应该像这样]
【解决方案2】:

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

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

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 的字典。

【讨论】:

  • 你能举一个将要发送的json的例子吗?
  • 嘿,我已经给了它,请查看[我正在尝试将其转换为]部分
猜你喜欢
  • 1970-01-01
  • 2019-04-01
  • 2013-02-04
  • 2019-01-08
  • 2023-01-20
  • 2021-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多