python - 列表中无意的随机顺序
问题描述
我正在尝试使用 JSON 对象的数据构建一个列表。但是,列表的顺序与 JSON 对象的顺序不匹配,并且几乎每次我运行代码时都会发生变化。
{
"project":{
"Projektnamen":{
"Server":{
"Server1":{
...
},
"Server2":{
...
},
"Server3":{
...
}
}
}
}
}
with open('json_data.json') as json_file:
# json CONFIG_JSON Konfigurationsdatei
CONFIG_JSON = json.load(json_file)
for key in CONFIG_JSON["project"]["Projektnamen"]["Server"]:
servernamen.append(key)
预期结果:servernamen = [Server1, Server2, Server3]
但是,顺序总是在变化。最后结果: servernamen = [Server3, Server1, Server2]
解决方案
您可以使用collections.OrderedDict
以下参数导入已排序的 JSON 数据json.load
:
from collections import OrderedDict
import json
r = json.load(open('json_data.json'), object_pairs_hook=OrderedDict)
推荐阅读
- python - 使用从不同行开始的 Pandas 处理多个 csv
- jms - AMQ 读取 simpleString 时出错,length=xxx 大于 readableBytes=yyy
- javascript - 父容器使用缩放效果转换时的画布渲染问题
- python - 如何使用两个单独的有效负载作为 Python 请求的参数
- cron - 如何在 Moodle 中将记录作为计划任务自动发送到 LRS
- r - 如果用户写入超过 1 列,如何从 Shiny 的数据框中选择列?
- php - 客户端生成的唯一 ID 与数据库唯一 ID
- java - 为什么while循环的经过时间值小于错误时间总和?
- outlook - 用户打开电子邮件时激活功能的 Outlook 插件
- email - 将 cpanel 电子邮件服务器与 Gsuite 一起使用