Search code examples
pythonjsondictionaryindexingdictionary-comprehension

Identify location of item in json file


Suppose I have the following json file. With data1["tenants"][1]['name'] I can select uniquename2. Is there a way to collect the '1' number by looping over the document?

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

in short: data1["tenants"][1]['name']= uniquename2 data1["tenants"][0]['name'] = uniquename How can I find out which number has which name. So if I have uniquename2 what number/index corresponds with it?


Solution

  • you can iterate over the tenants to map the index to the name

    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'])
    

    OUTPUT

    0 uniquename
    1 uniquename2