如何使用python将我的数据添加到json对象的开头

2024-05-02 21:27:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我在json文件中使用了以下代码

"destinations": [
     {
        "/abc/def": {

  "proxy_pass":"https://{{application_destination}}/abc/service$is_args$args",
            "host": "{{application_destination}}",

            }
        }
]

我必须将proxy\u pass的url添加到某个变量中,然后将该变量添加到 使用python代码的代理传递

if "proxy_pass" in location_details:
            proxy_pass = location_details[proxy_pass]
            location_details["set"] = "$backend " + proxy_pass
            location_details["proxy_pass"] = "$backend"

但我得到的输出是在代理通过后,设置值正在打印 那么,如何使用python将set值添加到json对象的开头呢


Tags: 文件代码backendjson代理applicationargslocation
1条回答
网友
1楼 · 发布于 2024-05-02 21:27:29

Pythondict对象在Python 3.7之前是无序的

您可以使用^{}

from collections import OrderedDict
import json


location_details = OrderedDict({
    "proxy_pass": "https://{{application_destination}}/abc/service$is_args$args",
    "host": "{{application_destination}}",
})

if "proxy_pass" in location_details:
    proxy_pass = location_details.pop('proxy_pass')
    location_details["set"] = "$backend " + proxy_pass
    location_details["proxy_pass"] = "$backend"

print(json.dumps(location_details, indent=4))

输出

{
    "host": "{{application_destination}}", 
    "set": "$backend https://{{application_destination}}/abc/service$is_args$args", 
    "proxy_pass": "$backend"
}

编辑

获得所需的订单

  1. set
  2. proxy_pass
  3. host

可以使用^{}host键移动到OrderedDict的末尾:

from collections import OrderedDict
import json


location_details = OrderedDict({
    "proxy_pass": "https://{{application_destination}}/abc/service$is_args$args",
    "host": "{{application_destination}}",
})

if "proxy_pass" in location_details:
    proxy_pass = location_details.pop('proxy_pass')
    location_details["set"] = "$backend " + proxy_pass
    location_details["proxy_pass"] = "$backend"
    location_details.move_to_end('host')

print(json.dumps(location_details, indent=4))

输出

{
    "set": "$backend https://{{application_destination}}/abc/service$is_args$args",
    "proxy_pass": "$backend",
    "host": "{{application_destination}}"
}

注意

也可以使用location_details.move_to_end(key, last=False)key移动到字典的开头

相关问题 更多 >