lis中的无意随机顺序

2024-09-29 22:01:35 发布

您现在位置: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]


Tags: 对象keyprojectconfigjson列表server顺序
2条回答

json.loads将JSON反序列化到dictionary对象中,dictionary对象是未排序的哈希表。你知道吗

您可以使用来自collectionsOrderedDict对键进行排序。 示例

from collections import OrderedDict

d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
new_d = OrderedDict(sorted(d.items()))

print(new_d)
# OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

您可以使用^{}json.load的参数导入已经排序的JSON数据:

from collections import OrderedDict
import json


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

相关问题 更多 >

    热门问题