Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I tried to access 'gold_spent` key in some dictionary made from JSON file.
Here is my code:
import json
import requests
response = requests.get("https://sky.shiiyu.moe/api/v2/profile/tProfile")
json_data = json.loads(response.text)
print(json_data['gold_spent'])
When I run this I get this "KeyError: 'gold_spent'"
I don't know what I am doing wrong, any help would be appreciated.
The data you are looking for is nested. See below.
print(json_data['profiles']['590cedda63e145ea98d44015649aba30']['data']['misc']['auctions_buy']['gold_spent'])
output
46294255
You experienced an exception because gold_spent isn't at all a key of first level, you need to investigate the structure to find it. Accessing non-existing key in the dictionary would always end with KeyError exception.
import json
import requests
response = requests.get("https://sky.shiiyu.moe/api/v2/profile/tProfile")
json_data = json.loads(response.text)
print(json_data.keys())
# dict_keys(['profiles'])
print(json_data['profiles'].keys())
# dict_keys(['590cedda63e145ea98d44015649aba30'])
print(json_data['profiles']['590cedda63e145ea98d44015649aba30'].keys())
# dict_keys(['profile_id', 'cute_name', 'current', 'last_save', 'raw', 'items', 'data'])
print(json_data['profiles']['590cedda63e145ea98d44015649aba30']['data']['misc']['auctions_buy']['gold_spent'])
# 46294255
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a project and want to access a url by python. If i have variable1=1 and variable2=2, I want an output to be like this:
www.example.com/data.php?variable1=1&variable2=2
How do I achieve this? Thanks!
Check this out:
try:
from urllib2 import urlopen # python 2
except:
from urllib.request import urlopen # python 3
vars = ['variable1=1', 'variable2=2']
for i in vars:
url = 'http://www.example.com/data.php?' + i
response = urlopen(url)
html = response.read()
print(html)
The first four lines import some code we can use to make a HTTP request.
Then we create a list of variables named vars.
Then we pass each of those variables into a loop; that loop will run once for each item in vars.
Next we build the url given the current value in vars.
Finally we get the html at that address and print it to the terminal.
You can use formate operation in python for string.
for example
variable1=1
variable1=1
url = 'www.example.com/data.php?variable1={}&variable2={}'.format(variable1,variable1)
or if you want to use the url with request then you can make a dict and pass it in request like this way
import requests
url = 'http://www.example.com/data.php'
data = {'variable1':'1','variable2':'2'}
r = requests.get(url,data)
and it will making request on this url
http://www.example.com/data.php?variable1=1&variable2=2
Try string formatting...
url = 'www.example.com/data.php?variable1={}&variable2={}'.format(variable1, variable2)
This means the 2 {} will be replaced with whatever you pass in .format(), which in this case is just the variables' values
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am pretty new to programing so I am sure this is not correct but its the best I can do based on my research. Thanks.
import pandas as pd
import numpy as np
import requests
import yelp
requests.get(https://api.yelp.com/v3/autocomplete?text=del&latitude=37.786882&longitude=-122.399972,headers={'Authorization: Bearer <API KEY that I have>'})
My noob self tells me this is a dictonary
headers={'Authorization: Bearer <API KeY>'}
I know this is prob 100% wrong so I would really love to learn more about using rest API's in Python. I am just doing this as a personal project. My overall goal is to be able to access yelps public data via API. For example, I want to get the reviews for business X.
Update
requests.get("https://api.yelp.com/v3/autocomplete?text=del&latitude=37.786882&longitude=-122.399972",headers={'Authorization: Bearer <API KEY>'})
I now get the following error
AttributeError: 'set' object has no attribute 'items'
You're definitely not 100% wrong #g_altobelli!
Let's take the example of getting reviews for business X, where X is one of my favorite restaurants -- la taqueria in San Francisco. Their restaurant id (which can be found in the url of their review page as the last element) is la-taqueria-san-francisco-2.
Now to our code:
You have the right idea using requests, I think your parameters might just be slightly off. It's helpful inititally to have some headers. Here's what I added:
import requests
API_KEY = "<my api key>"
API_HOST = 'https://api.yelp.com'
BUSINESS_PATH = '/v3/businesses/'
Then I created a function, that took in the business id and returned a jsonified result of the basic data. That looked like this:
def get_business(business_id):
business_path = BUSINESS_PATH + business_id
url = API_HOST + business_path + '/reviews'
headers = {'Authorization': f"Bearer {API_KEY}"}
response = requests.get(url, headers=headers)
return response.json()
Finally, I called the function with my values and printed the result:
results = get_business('la-taqueria-san-francisco-2')
print(results)
The output I got was json, and looked roughly like the following:
{'reviews': [{'id': 'pD3Yvc4QdUCBISy077smYw', 'url': 'https://www.yelp.com/biz/la-taqueria-san-francisco-2?hrid=pD3Yvc4QdUCBISy077smYw&adjust_creative=hEbqN49-q6Ct_cMosX68Zg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_reviews&utm_source=hEbqN49-q6Ct_cMosX68Zg', 'text': 'My second time here.. \nI love the Burito here it has the distinct taste of freshness.. we order super steak burito and boy it did not disappoint! everything...}
Does this help? Let me know if you have any more questions.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am parsing a huge JSON in python, i am parsing it step by step, i am stuck at a point and i can't figure out why the code is not running properly, my code is;
I want to get value of all the WHO_REGION for all the attr in an array, as i am not an expert in python programming..... here is the JSON, "http://apps.who.int/gho/athena/data/COUNTRY.json"
import json
from pprint import pprint
mylabel = []
mylabel2 = []
with open('C:\Users\Syed Saad Ahmed\Desktop\FL\COUNTRY.json') as data_file:
data = json.load(data_file)
for i in range(0,246):
mylabel.append(data["dimension"][0]["code"][i]["label"])
print mylabel
for j in range(0,246):
for k in range(0,21):
if(data["dimension"][0]["code"][j]["attr"][k]["category"]=='WHO_REGION'):
mylabel2.append(data["dimension"][0]["code"][j]["attr"][k]["value"])
print mylabel2
You can browse your JSON object using nested loops:
import json
obj = json.loads(data)
dimention_list = obj["dimension"]
for dimension in dimention_list:
code_list = dimension["code"]
for code in code_list:
attr_list = code["attr"]
for attr in attr_list:
if attr["category"] == "WHO_REGION":
print(attr["value"])
It is complex because each entry contains a list of something…
Of course, it's up to you to add some filtering.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm using the requests library in Python to do a post request, but I'm having a problem when I read a value from a spreadsheet.
The following code works (returns a 201 status code):
url = 'http://myport:8092//api/Accounts/1000/Users'
item = {"firstName": "John", "lastName": "Smith", "userName": "JSmith"}
r = requests.post(url, json = item)
print(r.status_code)
As soon as I read "item" from a cell in a spreadsheet, a 501 error code gets returned. When I print out "item" after reading it from the spreadsheet, the output matches the value for item shown above.
I haven't been able to find a solution, the only thing I can think of is that the problem is that it's being read as a string?
Do I need to convert it into a json object before I run the post?
501 is the error code for not implemented. It looks like the url you're sending to doesn't accept post requests. Is the url correct?
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to store some kind of persistent tracking to my application. Like for example ,
application.py supports 3 arguments, --firstarg --secondarg --thirdarg.
user can execute application.py using either one of the argument. I want to provide a feature where in user can track that he has already completed running the firstarg. In order to achieve this, i wanted to store a file called status.log, where the tracker will be stored.
Initially, status.log has
firstarg : 0
secondarg : 0
thirdarg : 0
once the user executes the first arg, it should turn the line , firstarg : 1
so when users wants, he can check if he has already completed running the firstarg or not.
Is it possible ?
I tried shelve, its not working for me for some reason. I am not seeing any logs written to the file.
Thanks.
I'd say use a JSON file as a persistent store and use the load and dump methods for reads and writes.
The JSON method is built in so all you need is to import it and use it:
import json
data_file = '/path/to/file'
# Load current state from file
contents = json.load(data_file)
# Do something
# ....
# ....
# Change values
contents['firstarg'] = firstarg
# Save to file
json.dump(contents, data_file)
Since you don't have a code sample, this is a simple approach