首页 > 解决方案 > 列表中无意的随机顺序

问题描述

我正在尝试使用 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]

标签: pythonlist

解决方案


您可以使用collections.OrderedDict以下参数导入已排序的 JSON 数据json.load

from collections import OrderedDict
import json


r = json.load(open('json_data.json'), object_pairs_hook=OrderedDict)

推荐阅读