1
\$\begingroup\$

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
...

asked Aug 30, 2019 at 20:31
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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)
answered Aug 30, 2019 at 21:52
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.