标识条目在json文件中的位置



假设我有以下json文件。对于data1["tenants"][1]['name'],我可以选择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']= uniquename2data1["tenants"][0]['name']= uniquename我怎么知道哪个号码有哪个名字?如果我有uniquename2,它对应的数字/索引是什么?

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

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

假设您已经将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

相关内容

  • 没有找到相关文章

最新更新