创建函数来解析特定键的 JSON,然后对其值应用 urlparse
Creating function to parse JSON for particular key, then apply urlparse on its value
我有一个 JSON 看起来像这样:
[
{
"weburl": "https://google.com/athens",
"location": "Greece"
},
{
"weburl": "https://google.com/rome",
"location": "Italy"
}
...
]
我想做的是创建一个函数将这个json传递给那个
- 在整个 json 和
中搜索关键字 "weburl" 的出现
- 调用 urlparse(value).hostname 替换每个 "weburl" 键旁边的字符串值以仅包含主机名,最后
- Return这整个修改json.
我在 Python 中执行此操作时遇到问题(特别是通过键、值进行导航以及对值调用 urlparse),如有任何帮助,我们将不胜感激!
谢谢。
因为在你的例子中它似乎是一个字典列表,假设 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
我有一个 JSON 看起来像这样:
[
{
"weburl": "https://google.com/athens",
"location": "Greece"
},
{
"weburl": "https://google.com/rome",
"location": "Italy"
}
...
]
我想做的是创建一个函数将这个json传递给那个
- 在整个 json 和 中搜索关键字 "weburl" 的出现
- 调用 urlparse(value).hostname 替换每个 "weburl" 键旁边的字符串值以仅包含主机名,最后
- Return这整个修改json.
我在 Python 中执行此操作时遇到问题(特别是通过键、值进行导航以及对值调用 urlparse),如有任何帮助,我们将不胜感激!
谢谢。
因为在你的例子中它似乎是一个字典列表,假设 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