简体   繁体   English

如何使用 python 和索引号从 json 文件中获取特定数据

[英]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:我想从像这样的 json 文件中获取 url :

[
    {
        "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?有什么方法可以使用“索引”号来获取 url?

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.用您的 json object 和指定的索引调用此 function ,它应该可以解决您的问题。 It simply loops over the list and checks each dictionary for its index value.它只是遍历列表并检查每个字典的索引值。

You can achieve this by creating a dictionary in python, which requires looping over the list when indexing.您可以通过在 python 中创建一个字典来实现这一点,这需要在索引时遍历列表。

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.创建字典后,从中访问元素将比每次循环遍历整个列表要快得多。

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例如,您想要索引 6、7 和 11 的 url

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM