创建函数来解析特定键的JSON,然后对其值应用urlparse

2024-10-06 15:28:05 发布

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

我有一个类似这样的JSON:

[
    {
    "weburl": "https://google.com/athens",
    "location": "Greece"
    },
    {
    "weburl": "https://google.com/rome",
    "location": "Italy"
    }
    ...
]

我想做的是创建一个函数,将这个json传递给

  1. 在整个json中搜索关键字“weburl”的出现情况,以及
  2. 调用urlparse(value).hostname来替换每个“weburl”键旁边的字符串值,以便只包含hostname,最后
  3. 返回整个修改的json

我在Python中很难做到这一点(特别是在key、value中导航并调用urlparse),如果有任何帮助,我将不胜感激

谢谢


Tags: 函数httpscomjsonvaluegooglelocationhostname
1条回答
网友
1楼 · 发布于 2024-10-06 15:28:05

因为在您的示例中,它似乎是一个字典列表,假设Python-3.x,我建议您尝试:

import json
from urllib.parse import urlparse

def f(raw_json):
    dict_list = json.loads(raw_json) # assuming raw_json is a string.
    # if raw_json is already a parsed json then start here:
    for dic in dict_list:
        try:
            dic['weburl'] = urlparse(dic['weburl']).hostname
        except KeyError:
            pass
    return dict_list    

相关问题 更多 >