'How to get a specific data from a json file using python and index number

I want to get an url from a json file like this one:

[
    {
        "Index": 6,
        "Title": "A Simple Monitoring",
        "URL": "http://www.vn-meido.com/k1/index.php?PHPSESSID=4e30s552gamla57pl6hdhe2cn4&topic=1497.msg20688"
    },
    {
        "Index": 7,
        "Title": "A Simple Survey",
        "URL": "http://www.vn-meido.com/k1/index.php?PHPSESSID=4e30s552gamla57pl6hdhe2cn4&topic=1283.0"
    },
]

is there any method using the "Index" number to get the url?



Solution 1:[1]

Ah, so it's a list of dictionaries, seems like you could use a list comprehension to effectively "filter" the list.

eg you want the urls for index 6, 7, & 11

wanted_url_ids = [6, 7, 11]
[url_dict for url_dict in json_file if url_dict[index] in wanted_url_ids]

Solution 2:[2]

You can achieve this by creating a dictionary in python, which requires looping over the list when indexing.

dat = [
    {
        "Index": 6,
        "Title": "A Simple Monitoring",
        "URL": "http://www.vn-meido.com/k1/index.php?PHPSESSID=4e30s552gamla57pl6hdhe2cn4&topic=1497.msg20688"
    },
    {
        "Index": 7,
        "Title": "A Simple Survey",
        "URL": "http://www.vn-meido.com/k1/index.php?PHPSESSID=4e30s552gamla57pl6hdhe2cn4&topic=1283.0"
    },
]

dat_dict = {}

for item in dat:
    dat_dict[item['Index']] = item['URL']

print(dat_dict[6])
print(dat_dict[7])

After the dictionary was created, accessing elements from it would be much faster than looping through on the entire list every time.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sharpie
Solution 2 Jett Chen