python - 如何使用 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对象的开头
解决方案
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"
}
编辑
获得所需的订单
set
proxy_pass
host
您可以使用OrderedDict.move_to_end
将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
到字典的开头
推荐阅读
- python - Discord Self-Bot:加入服务器/公会时直接向用户发送消息
- javascript - Emscripten:使用 pthread 时的自定义消息处理程序
- biztalk - Can BizTalk be used to fetch data from a dynamic URL?
- html - 如何将容器和标签与 Bootstrap 中的复选框对齐?
- docker-compose - 如何从另一个 docker 容器运行 mecab
- azure - 如何使用 Azure Databricks 访问 Azure Cosmos DB 分析存储?
- c# - 可以调用 WPF 类型编辑器的构造函数(从 ITypeEditor 继承)?
- php - 获取库存数量的 SQL SELECT 查询不在函数中返回值(但来自 phpMyAdmin)
- postgresql - 返回整数和布尔值的二维数组
- vue.js - 嵌套路由在 vuejs 应用程序中对我不起作用