When using python and steam api trying to get a certain value using data = profile['gameextrainfo'] profile has the value of the API which is.
d = {"response":
{"players":[
{"steamid":"76561199446676130",
"communityvisibilitystate":3,
"profilestate":1,
"personaname":"S7 WatchDog",
"profileurl":"https://steamcommunity.com/profiles/76561199446676130/",
"avatar":"https://avatars.akamai.steamstatic.com/415bd0e2ddd5d8e99309eec6d7a2566cbb09022d.jpg","avatarmedium":"https://avatars.akamai.steamstatic.com/415bd0e2ddd5d8e99309eec6d7a2566cbb09022d_medium.jpg","avatarfull":"https://avatars.akamai.steamstatic.com/415bd0e2ddd5d8e99309eec6d7a2566cbb09022d_full.jpg",
"avatarhash":"415bd0e2ddd5d8e99309eec6d7a2566cbb09022d",
"personastate":1,
"primaryclanid":"103582791429521408",
"timecreated":1671522419,
"personastateflags":0,
"gameextrainfo":"Counter-Strike: Global Offensive",
"gameid":"730"}]
}
}
I cannot seem to filter out any key. I've tried all of them and python just fails to find them. Any ideas
Tried all keys. Tried using requests python module
You could use the json module to parse the response and access the individual data points. For example:
import json
data = json.loads(profile)
gameextrainfo = data['response']['players'][0]['gameextrainfo']
print(gameextrainfo)
Related
I'm using an API that is giving me and output formatted as
['{"quote":{"symbol":"AAPL"', '"companyName":"Apple Inc."', '"primaryExchange":"Nasdaq Global Select"', '"sector":"Technology"', '"calculationPrice":"close"', '"open":367.88', '"openTime":1593696600532', '"close":364.11', '"closeTime":1593720000277', '"high":370.47', '"low":363.64', '"latestPrice":364.11'}]
...(it keeps going like this with many more categories.)
I am attempting to pull out only the latest price. What would be the best way to do that?
This is what I have but I get a bunch of errors.
string = (data.decode("utf-8"))
data_v = string.split(',')
for word in data_v[latestPrice]:
if word == ["latestPrice"]:
print(word)
print(data_v)
Judging by the output this is JSON. To parse this easily use the JSON module (see https://docs.python.org/3/library/json.html ).
If I'm correct you got this output from Yahoo Finance, if this indeed the case don't fetch and parse it manually but use the yfinance module (see https://pypi.org/project/yfinance/ )
You will have to use JSON module to parse this JSON string. You can convert it into dictionary then. I have indented the JSON code for ease of understanding. You can use the following approach,
import json
text_to_parse = """
{"quote":
{
"symbol":"AAPL",
"companyName":"Apple Inc.",
"primaryExchange":"Nasdaq Global Select",
"sector":"Technology",
"calculationPrice":"close",
"open":367.88,
"openTime":1593696600532,
"close":364.11,
"closeTime":1593720000277,
"high":370.47,
"low":363.64,
"latestPrice":364.11
}
}
"""
parsed_dict = json.loads(text_to_parse)
print(parsed_dict["quote"]["latestPrice"])
When the program is run, it outputs 364.11
I'm trying to get my Python script to parse some data (the price) from a specific json file on a site, but I am unable to get it working.
It can extract the whole page fine, but it cannot extract certain data just by itself.
Here is the JSON I am trying to extract data from:
[{
"id": 1696146,
"name": "Genos",
"photo_url": "https://hobbydb-production.s3.amazonaws.com/processed_uploads/collectible_photo/collectible_photo/image/324461/1556082253-24867-7610/Genos_Vinyl_Art_Toys_60fb245b-1af9-4ad1-a5a2-c90d3e8291a6_medium.jpg",
"preorder": false,
"price": "$40.00",
"price_after_discount": "$40.00",
"seller_username": "BatmanPajamas",
"url": "https://www.hobbydb.com/marketplaces/2/cart/1696146"
}]
Here is the code I have got that allows me to get the entire json:
import urllib.request, json
withurllib.request.urlopen("https://www.hobbydb.com/api/collectibles/for_sale_search?limit=5&original_site_id=10748&market_id=2") as url:
data = json.loads(url.read().decode())
print(data)
I have tried various pieces of code, but everytime I get:
TypeError: list indices must be integers or slices, not str
Any ideas how I can parse the price from this JSON?
The outer brackets ([]) indicate the response returns a list of items. So, you need to loop over the indices of the list, then you can access what you're trying to access. Here's how I do it with requests
import requests
resp = requests.get("https://www.hobbydb.com/api/collectibles/for_sale_search?limit=5&original_site_id=10748&market_id=2")
#requests has built-in support for json, so no need to import json module
for product in resp.json():
print(product["price"])
To iterate over json array:
for item in data:
for keys in item.keys():
print(item[keys])
to display only price
for item in data:
print(item['price'])
I think the problem you are having is because this JSON object starts with an array (which will be a list once we load it as a Python object). First, you need to use the json library from the standard lib. Then, you have to access the object using the list index, then the dict keys.
Try this:
import urllib.request, json
with urllib.request.urlopen("https://www.hobbydb.com/api/collectibles/for_sale_search?limit=5&original_site_id=10748&market_id=2") as url:
data = json.loads(url.read().decode())
print(data)
toy = data[0]
price = toy['price']
Also, keep in mind that the with keyword creates a context for parsing the JSON data, so once your script moves on to code outside of this context, you won't be able to access your price variable any longer, so you might want to assign or set that value to to another variable created outside of that context.
I have used tweepy user timeline API to extract information for some users. Here is the link to the file.
The content of the file is in string format. I tried to load the same using JSON.loads(<string>) but it is showing the error
ValueError: Expecting property name: line 1 column 2 (char 1)
I need to make the string to work as a dict/json so that I can iterate on the keys.
Can we see the full code of how you implemented the API call, but also try converting it into a collection first. try
from collection import Counter
Counter(data)
So I'm trying to learn Python here, and would appreciate any help you guys could give me. I've written a bit of code that asks one of my favorite websites for some information, and the api call returns an answer in a dictionary. In this dictionary is a list. In that list is a dictionary. This seems crazy to me, but hell, I'm a newbie.
I'm trying to assign the answers to variables, but always get various error messages depending on how I write my {},[], or (). Regardless, I can't get it to work. How do I read this return? Thanks in advance.
{
"answer":
[{"widgets":16,
"widgets_available":16,
"widgets_missing":7,
"widget_flatprice":"156",
"widget_averages":15,
"widget_cost":125,
"widget_profit":"31",
"widget":"90.59"}],
"result":true
}
Edited because I put in the wrong sample code.
You need to show your code, but the de-facto way of doing this is by using the requests module, like this:
import requests
url = 'http://www.example.com/api/v1/something'
r = requests.get(url)
data = r.json() # converts the returned json into a Python dictionary
for item in data['answer']:
print(item['widgets'])
Assuming that you are not using the requests library (see Burhan's answer), you would use the json module like so:
data = '{"answer":
[{"widgets":16,
"widgets_available":16,
"widgets_missing":7,
"widget_flatprice":"156",
"widget_averages":15,
"widget_cost":125,
"widget_profit":"31",
"widget":"90.59"}],
"result":true}'
import json
data = json.loads(data)
# Now you can use it as you wish
data['answer'] # and so on...
First I will mention that to access a dictionary value you need to use ["key"] and not {}. see here an Python dictionary syntax.
Here is a step by step walkthrough on how to build and access a similar data structure:
First create the main dictionary:
t1 = {"a":0, "b":1}
you can access each element by:
t1["a"] # it'll return a 0
Now lets add the internal list:
t1["a"] = ["x",7,3.14]
and access it using:
t1["a"][2] # it'll return 3.14
Now creating the internal dictionary:
t1["a"][2] = {'w1':7,'w2':8,'w3':9}
And access:
t1["a"][2]['w3'] # it'll return 9
Hope it helped you.
I'm starting to code in python using pysimplesoap. Testing first against a service available on Internet. I'm stuck trying to parse the result of the Soap query.
I coded:
#!/usr/bin/python
from pysimplesoap.client import SoapClient
import pysimplesoap
import logging
logging.basicConfig()
client=SoapClient(wsdl="http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx?wsdl",trace=True)
response = client.VerifyEmail(email="a-valid-gmail-address#gmail.com",LicenseKey="?")
print response
I get the following which means the Soap request was positive:
{'VerifyEmailResult': {'GoodEmail': True, 'LastMailServer': u'gmail-smtp-in.l.google.com', 'ResponseText': u'Mail Server will accept email', 'ResponseCode': 3}}
I now want to extract the value of GoodEmail which is equal to True from "response" and store it in a variable named "result".
I tried various things, without success.
I must admit I'm very new to Python, and would appreciate help from a knowledgeable person!
What you get as the response is a Python dict. You can access the GoodEmail value like that:
result = response['VerifyEmailResult']['GoodEmail']
You can read more about Python data types here: http://docs.python.org/2/library/stdtypes.html