I am trying to split and assign the url's to the variable, I am getting the desired result but I know there is a way where I can improvise the current code.
JSON FILE
{
"Result": [
"Url::Link::Url1",
"Url::Link::Url2",
"Url::Link::Url3",
"Url::Link::Url4",
"Url::Link::Url5",
"Url::Link::Url6",
"Url::Link::Url7"
],
"Record": [
"Record::Label::Music1",
"Record::Label::Music2",
"Record::Label::Music3"
],
}
import requests
import json
url = "http:mywebsite.com"
headers = {
'User-Agent': "PostmanRuntime/7.15.2",
'Accept': "*/*",
'Cache-Control': "no-cache"
}
result= requests.get("GET", url, headers=headers).json()
url1 = []
url2 = []
url3 = []
for i in result['Result'][0:1]:
url1.append(i.split('::')[2])
for i in result['Result'][1:2]:
url1.append(i.split('::')[2])
for i in result['Result'][2:3]:
url1.append(i.split('::')[2])
Output
url1=Url1
url2=Url2
...
1 Answer 1
As long as there's nothing special about the nth URL, you can just store the URLs in one list:
urls = []
for result_string in result["Result"]:
url = result_string.split("::")[2]
urls.append(url)
If there is something unique information you want to capture about the nth URL, you could store the URLs in a dictionary to map the URL to its type.
def url_type(n):
"""returns the type of url given its index n in the response"""
#example
if n == 1:
return 'url-type-a'
return 'url-type-b'
urls = {
"url-type-a": [],
"url-type-b": []
}
for i, result_string in enumerate(result["Result"]):
url = result_string.split("::")[2]
urls[url_type(i)].append(url)