This question already has an answer here:
How to extract values from a Python request
(1 answer)
Closed 6 months ago.
How do I get a specific element from requests response.text
{"status":"success","data":{"id":30815925}}
im need to get ID from that output
You can import the json package and simply do
import json
id = json.loads(response.text)["data"]["id"]
This will convert response.text from a string to a python dictionary, and the id will be inside the variable id
Related
This question already has answers here:
Loading JSON object in Python using urllib.request and json modules
(3 answers)
Closed 11 months ago.
URL = "API URL"
response = urllib.request.urlopen(URL)
standards = response.read() #returning type <bytes>
standards = standards.decode('utf-8') #converting type <str>
I actually want to read through the data and extract the values of "referenceNumber" & "title" from the data given below, I have 755 records of same structure. I want to extract the above given fields for each record.
[{"larsCode":0,"referenceNumber":"ST0870","title":"Business support assistant","status":"Withdrawn","url":"https://www.instituteforapprenticeships.org/api/apprenticeshipstandards/0","versionNumber":"0.0","change":"Withdrawn","changedDate":"2019-07-31T00:00:00","earliestStartDate":null,"latestStartDate":null,"latestEndDate":null,"overviewOfRole":"","level":2,"typicalDuration":0,"maxFunding":0,"route":"Business and administration","keywords":["Business","support","assistant","admin","office","office administration"],"jobRoles":[],"entryRequirements":"","assessmentPlanUrl":"","ssa1":"","ssa2":"","version":"0.0","standardInformation":"","occupationalSummary":"","knowledges":[],"behaviours":[],"skills":[],"options":[],"optionsUnstructuredTemplate":[]]
The server returns json encoded bytes. Python has a module for json.
You dont need to convert it to str in order to decode the json bytes.
Look at the python documentation for handling json objects.
Specifically json.loads for handling str or json.load for handling file like objects.
https://docs.python.org/3/library/json.html#json.loads
Just an fyi, your response is a list of objects so json.loads will return a list of dict.
This question already has answers here:
How to concatenate (join) items in a list to a single string
(11 answers)
Closed 2 years ago.
I'm relatively new to python,
I built a webscraper that gets the top posts of a website and stores them in a list in python like this:
T = ["post1","post2","post3,"post4"]
To send the push notification with pushover I installed the pushover module that works like this:
from pushover import Pushover
po = Pushover("My App Token")
po.user("My User Token")
msg = po.msg("Hello, World!")
po.send(msg)
I want to send the list as a message with format, like this:
Top Posts:
1. post 1
2. post 2
3. post 3
4. post 4
I tried this:
msg = po.msg("<b>Top Posts:</b>\n\n1. "+T[0]+"\n"+"2. "+T[1]+"\n"+"3. "+T[2]+"\n"+"4. "+T[3]")
The above solution works, however the number of posts will be variable so that's not a viable solution.
What can I do to send the message with the correct formatting knowing that the number of posts in the list will vary from time to time?
Using str.join and a comprehension using enumerate:
msg = po.msg("<b>Top Posts:</b>\n\n" + '\n'.join(f'{n}. s {n}' for n, s in enumerate(T, 1)))
This question already has answers here:
Print to the same line and not a new line? [duplicate]
(19 answers)
Closed 3 years ago.
I am using an API where I can fetch data with. From the data output I am trying to get specific portions so I can place it nicely in a formatted text.
I want to fetch the data every 5 seconds, so I get fresh info. I do not want that the data is prompted below the output from the first run, but rather replace the current value(s) for the updated value(s).
As I'm pretty bad with python, I hope someone can give me some advice.
import requests
import threading
def dostuff()
threading.Timer(5.0, dostuff).start()
r = requests.get('https://api')
data = r.json()
print("Amount:", data['amount'])
print("Games played:", data['matches'])
dostuff()
This works fine. It just keeps posting the output under each other.
I wish to have everything static, except the data['amount'], and data['matches'], which should keep updating without actually posting it on newlines. I have tried resolving this by clearning the screen, but that is not the desired solution.
Just add end='\r' to your print statement:
import requests
import threading
import random
def dostuff():
threading.Timer(1.0, dostuff).start()
# replaced as actual api not posted
data = {
'amount': round(random.random(), 2),
"matches": round(random.random(), 2)
}
print("Amount: {} Games played: {}".format(
data['amount'],
data['matches']
), end='\r')
dostuff()
This question already has answers here:
HTTP requests and JSON parsing in Python [duplicate]
(8 answers)
Closed 3 years ago.
I have a REST Api that only renders this data
data: "xxxxxxxxxxxxxxx"
I need to store this XXXXXXXXXX value in some variable using python, but I could only code and reach to the part where I get this value data:"xxxxxxxxxxxxxx"
my code is as follows
r = requests.get('url', headers=headers, verify=False)
logger.info(r)
which gives the output data: "xxxxxxxxxxxxxxx"
How can i fetch only XXXXXXXXXXXX from this json output ?
As simple as this could work for you.
r = requests.get('url', headers=headers, verify=False).json()
print(r['data'])
This question already has answers here:
Why can't Python parse this JSON data? [closed]
(3 answers)
Closed 4 years ago.
[{"sku":43900,"name":"Batteries (4-Pack)","type":"HardGood","category": [{"id":"pc5","name":"Housewares"}]]
this is in json file.
i want to load this and make a dictionary in Python from this input.i tired to load but confused how to create dictionary from this input.
import json
data = []
json_file=open ('prod.json')
json_str=json_file.read()
json_data=json.loads(json_str)
for items in json_data:
print(items['name'])
import json
s = '[{"sku":43900,"name":"Batteries (4-Pack)","type":"HardGood","category": [{"id":"pc5","name":"Housewares"}]}]'
list_of_dicts = json.loads(s)
Your json was invalid; I added a } in the right place.