Python:从具有相同名称的列表中解析json数据

2024-06-17 10:36:06 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有下一个json,我只想得到github链接和twitter链接,而不需要foursquare和gravatar链接。你知道吗

当然,有时候json数据会改变,如果找不到foursquare的url,github会成为第一个,twitter会成为第二个。其他的(github或twitter)也一样。你知道吗

如果github和twitter的url与json中的位置不同,如何获取它们?你知道吗

{ "socialProfiles": [
    {
        "type": "foursquare",
        "typeId": "foursquare",
        "typeName": "Foursquare",
        "url": "https://foursquare.com/user/somerandomuser",
        "id": "554225246246"
    },
    {
        "type": "github",
        "typeId": "github",
        "typeName": "Github",
        "url": "https://github.com/somerandomuser",
        "username": "somerandomuser"
    },
    {
        "type": "gravatar",
        "typeId": "gravatar",
        "typeName": "Gravatar",
        "url": "https://gravatar.com/somerandomuser",
        "username": "somerandomuser",
        "id": "132341667"
    },
    {
        "bio": " This is a bio of a random user",
        "followers": 543,
        "following": 222,
        "type": "twitter",
        "typeId": "twitter",
        "typeName": "Twitter",
        "url": "https://twitter.com/somerandomuser",
        "username": "somerandomuser",
        "id": "41414515335"
    }
]

}


Tags: httpsgithubcomidjsonurl链接type
3条回答
for social_profile in data["socialProfiles"]:
    for link in social_profile:
        if link['typeId'] == "twitter" or link['typeId'] == "github":
           print (link["url"])

使用简单的迭代。你知道吗

例如:

checkList = ["twitter", "github"]
for i in data["socialProfiles"]:
    if i["typeId"] in checkList:    #Check if typeid is in your check-list
        print(i["url"])

输出:

https://github.com/somerandomuser
https://twitter.com/somerandomuser
  • data是你的字典。你知道吗

您可以使用dict comprehension来创建另一个dict,只使用您需要的url,在本例中是twittergithub

search = ['github', 'twitter']

urls = {dct['type']: dct['url'] for dct in data.get('socialProfiles', []) if dct['type'] in search}
print(urls)                           

输出

{
    'github': 'https://github.com/somerandomuser',
    'twitter': 'https://twitter.com/somerandomuser'
}

然后你就可以得到你需要的url。你知道吗

print(urls['github'])

# Output
# https://github.com/somerandomuser

相关问题 更多 >