确定项目在 json 文件中的位置

Identify location of item in json file

假设我有以下 json 文件。使用 data1["tenants"][1]['name'] 我可以 select uniquename2。有没有办法通过遍历文档来收集“1”号?

{
    "tenants": [{
            "key": "identifier",
            "name": "uniquename",
            "image": "url",
            "match": [
                "identifier"
            ],
            "tags": [
                "tag1",
                "tag2"
            ]
        },
        {
            "key": "identifier",
            "name": "uniquename2",
            "image": "url",
            "match": [
                "identifier1",
                "identifier2"
            ],
            "tags": ["tag"]
        }
    ]
}

简而言之:data1["tenants"][1]['name']= uniquename2 data1["tenants"][0]['name'] = uniquename 我怎样才能找出哪个号码有哪个名字。那么,如果我有 uniquename2,number/index 对应的是什么?

假设,你已经把你的 json 变成了字典,这就是你如何获得列表中第一次出现的名字的索引(这取决于名字实际上是唯一的):

data = {
    "tenants": [{
            "key": "identifier",
            "name": "uniquename",
            "image": "url",
            "match": [
                "identifier"
            ],
            "tags": [
                "tag1",
                "tag2"
            ]
        },
        {
            "key": "identifier",
            "name": "uniquename2",
            "image": "url",
            "match": [
                "identifier1",
                "identifier2"
            ],
            "tags": ["tag"]
        }
    ]
}

def index_of(tenants, tenant_name):
    try:
        return tenants.index(
            next(
                tenant for tenant in tenants
                if tenant["name"] == tenant_name
            )
        )
    except StopIteration:
        raise ValueError(
            f"tenants list does not have tenant by name {tenant_name}."
        )

index_of(data["tenants"], "uniquename")  # 0

您可以遍历租户以将索引映射到名称

data = {
    "tenants": [{
            "key": "identifier",
            "name": "uniquename",
            "image": "url",
            "match": [
                "identifier"
            ],
            "tags": [
                "tag1",
                "tag2"
            ]
        },
        {
            "key": "identifier",
            "name": "uniquename2",
            "image": "url",
            "match": [
                "identifier1",
                "identifier2"
            ],
            "tags": ["tag"]
        }
    ]
}

for index, tenant in enumerate(data['tenants']):
    print(index, tenant['name'])

输出

0 uniquename
1 uniquename2