首页 > 解决方案 > 如何使用 python 将我的数据添加到 json 对象的开头

问题描述

我有带有以下代码的json文件

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

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

            }
        }
]

我必须将 proxy_pass 的 url 添加到某个变量,然后使用 python 代码将该变量添加到 proxy_pass

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

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

标签: pythonjsonamazon-web-servicesaws-lambda

解决方案


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

您可以使用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"

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

您可以使用OrderedDict.move_to_endhost键移动到末尾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到字典的开头


推荐阅读