Reputation: 13
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?
Upvotes: 0
Views: 447
Reputation: 73
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]
Upvotes: 1
Reputation: 382
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.
Upvotes: 0
Reputation: 1376
def get_url_by_index(json_list, i):
for dictionary in json_list:
if dictionary['Index'] == i:
return dictionary['URL']
Call this function with your json object and the specified index and it should solve your issue. It simply loops over the list and checks each dictionary for its index value.
Upvotes: 0