I'm new in this Python world, I'm trying to use an API to make basic currency calculations. I can get the output like:
{'USD': 1.13}
this but I want it just to be
1.13
The code:
import requests
inputCurrency = 'EUR'
outputCurrency = 'USD'
p = {"inpc":inputCurrency, "outc":outputCurrency}
url = 'https://somewebsite/api/data'
r = requests.get(url, params=p)
print(r.json())
The server returned a JSON object. The .json() method of your r response decodes it, and returns the decoded object, which is a Python dict.
You want the value corresponding to the 'USD' key.
Just do:
import requests
inputCurrency = 'EUR'
outputCurrency = 'USD'
p = {"inpc":inputCurrency, "outc":outputCurrency}
url = 'https://somewebsite/api/data'
response = requests.get(url, params=p)
json_data =response.json()
print(json_data['USD'])
If the structure of the data is more complicated, as in your comment:
json_data = { "status": 1, "data": [ { "time": "2015-08-30T07:56:28.000Z", "usd": 1.17 }, { "time": "2015-08-30T08:56:28.000Z", "usd": 1.27 }, { "time": "2015-08-30T09:56:28.000Z", "usd": 1.28 }]}
you could extract the relevant part:
data = json_data['data']
which is a list of dictionaries. You can then print the first one:
print(data[0]['usd'])
# 1.27
or print them all:
for day_value in data:
print(day_value['usd'])
Related
Here I am trying to get the XLM volume change per second! I got the API but when printing it gives me all the values! Clearly this is not what I really want all I want is the "volume" value!
CODE
import time, base64, hmac, hashlib, requests, json
apiKey = "public api goes here"
apiSecret = "private api goes here"
apiSecret = base64.b64decode(apiSecret)
stamp = str(int(time.time())*1000)
data = "{}{}".format(apiKey, stamp).encode('utf-8')
signature = hmac.new(apiSecret, data, hashlib.sha256).digest()
signature = base64.b64encode(signature)
headers= {
"X-PCK": apiKey,
"X-Stamp": str(stamp),
"X-Signature": str(base64.b64encode(signature).decode('utf-8')),
"Content-Type": "application/json "}
base = "https://api.btcturk.com"
method = "/api/v2/ticker?pairSymbol=XLM_TRY"
uri = base+method
result = requests.get(url=uri)
result = result.json()
print(json.dumps(result, indent=2))
OUTPUT
{
"data": [
{
"pair": "XLMTRY",
"pairNormalized": "XLM_TRY",
"timestamp": 1610020217912,
"last": 2.45,
"high": 3.35,
"low": 2.0,
"bid": 2.4489,
"ask": 2.45,
"open": 2.1786,
"volume": 551009229.0058,
"average": 2.4422,
"daily": 0.2714,
"dailyPercent": 12.46,
"numeratorSymbol": "XLM",
"order": 1000
}
],
"success": true,
"message": null,
"code": 0
WANTED OUTPUT
"volume": 551009229.0058
In order to get the "volume" entry you just need to navigate through the structures:
result = requests.get(url=uri)
result = result.json()
print(result["data"][0]["volume"])
There is no need to convert result back to json. The call to request.json() converts the json string returned in the requests.get() to a python data structure, namely a dict with a "data" entry which has a list with one entry in which is another dict where the entry "volume" is located.
So I am using the urban dictionary api, and the code works perfectly as I would like: I'm going to use chicken as my term.
import json
import requests
url = "https://mashape-community-urban-dictionary.p.rapidapi.com/define"
querystring = {"term":"chicken"}
headers = {
'x-rapidapi-host': "mashape-community-urban-dictionary.p.rapidapi.com",
'x-rapidapi-key': "KEY"
}
response = requests.request("GET", url, headers=headers, params=querystring)
json_data = response.text
json_object = json.loads(json_data)
print(json.dumps(json_object, indent = 4))
If I run this, I get the following which is the correct output, but I want to only print out the definition.
{
"list": [
{
"definition": "A [kilogram] of [cocain]. Dealers started calling kilos \"[birds]\" which then evolved into \"chicken.\"",
"permalink": "http://chicken.urbanup.com/1180537",
"thumbs_up": 2947,
"sound_urls": [
"http://api.twilio.com/2008-08-01/Accounts/ACd09691b82112e4b26fce156d7c01d0ed/Recordings/RE18c37ff43a6fc6dce8d9d533e7e4042b"
],
"author": "DEKE",
"word": "chicken",
"defid": 1180537,
"current_vote": "",
"written_on": "2005-04-11T11:41:04.000Z",
"example": "Person 1) [How much] you [got left]?\r\n\r\nPerson 2) A [quarter] chicken.",
"thumbs_down": 941
},
{
"definition": "To lack courage and [bravery]. [Unskilled], stupid, afraid, loser, [coward]",
"permalink": "http://chicken.urbanup.com/7399878",
"thumbs_up": 180,
"sound_urls": [
"http://api.twilio.com/2008-08-01/Accounts/ACd09691b82112e4b26fce156d7c01d0ed/Recordings/RE18c37ff43a6fc6dce8d9d533e7e4042b"
],
"author": "Freak Out Guy",
"word": "chicken",
"defid": 7399878,
"current_vote": "",
"written_on": "2013-12-10T16:49:06.660Z",
"example": "He was so afraid she [thought] he was [a chicken].",
"thumbs_down": 49
}
]
}
I've seen that you can do print(json_object['list'][0]['definition']), but it only prints out the first definition. How can I print out all the instances of definition like:
Definition 1: A [kilogram] of [cocain]. Dealers started calling kilos \"[birds]\" which then evolved into \"chicken.\"
Definition 2: To lack courage and [bravery]. [Unskilled], stupid, afraid, loser, [coward]
for idx, entry in enumerate(json_object['list'], 1):
print(f'Definition {idx}: {entry["definition"]}')
output
Definition 1: A [kilogram] of [cocain]. Dealers started calling kilos "[birds]" which then evolved into "chicken."
Definition 2: To lack courage and [bravery]. [Unskilled], stupid, afraid, loser, [coward]
You dont need to use the dump, u can use the json_object instead. Like this:
import json
import requests
url = "https://mashape-community-urban-dictionary.p.rapidapi.com/define"
querystring = {"term":"chicken"}
headers = {
'x-rapidapi-host': "mashape-community-urban-dictionary.p.rapidapi.com",
'x-rapidapi-key': "KEY"
}
response = requests.request("GET", url, headers=headers, params=querystring)
json_data = response.text
json_object = json.loads(json_data)
#json_object = json.dumps(json_object, indent = 4)
print(json_object["list"][0]["definition"]) # you can use the for statement to get all the definitions
(Edit) All the definitions example:
import json
import requests
url = "https://mashape-community-urban-dictionary.p.rapidapi.com/define"
querystring = {"term":"chicken"}
headers = {
'x-rapidapi-host': "mashape-community-urban-dictionary.p.rapidapi.com",
'x-rapidapi-key': "KEY"
}
response = requests.request("GET", url, headers=headers, params=querystring)
json_data = response.text
json_object = json.loads(json_data)
#json_object = json.dumps(json_object, indent = 4)
for i in json_object["list"]:
print(i["definition"])
I am trying to extract data from an API with python.
With this code, I am trying to print the content of dictionaries within a list.
response = requests.get(url, params=payload)
data = response.json()
log = json.dumps(data['result'], indent = 1)
print log
So far so good, it prints:
[
{
"line": "something#gmail.com:birthdaydate"
},
{
"line": "something#gmail.com:birthdaydate"
},
{
"line": "something#gmail.com:birthdaydate"
},
]
Is there a way for the output to look like below?
"something#gmail.com:birthdaydate"
"something#gmail.com:birthdaydate"
"something#gmail.com:birthdaydate"
Try this one:
response = requests.get(url, params=payload)
data = response.json()
log = data['result']
for l in log:
print(l["line"])
I'm trying to parse a website with the requests module:
import requests
some_data = {'a':'',
'b':''}
with requests.Session() as s:
result = s.post('http://website.com',data=some_data)
print(result.text)
The page is responding as below:
{
"arrangetype":"U",
"list": [
{
"product_no":43,
"display_order":4,
"is_selling":"T",
"product_empty":"F",
"fix_position":null,
"is_auto_sort":false
},
{
"product_no":44,
"display_order":6,
"is_selling":"T",
"product_empty":"F",
"fix_position":null,
"is_auto_sort":false
}
],
"length":2
}
I found that instead of parsing full HTML, it would be better to deal with the response as all the data I want is in that response.
What I want to get is a list of the values of product_no, so the expected result is:
[43,44]
How do I do this?
Convert your JSON response to a dictionary with json.loads(), and collect your results in a list comprehension.
Demo:
from json import loads
data = """{
"arrangetype":"U",
"list": [
{
"product_no":43,
"display_order":4,
"is_selling":"T",
"product_empty":"F",
"fix_position":null,
"is_auto_sort":false
},
{
"product_no":44,
"display_order":6,
"is_selling":"T",
"product_empty":"F",
"fix_position":null,
"is_auto_sort":false
}
],
"length":2
}"""
json_dict = loads(data)
print([x['product_no'] for x in json_dict['list']])
# [43, 44]
Full Code:
import requests
from json import loads
some_data = {'a':'',
'b':''}
with requests.Session() as s:
result = s.post('http://website.com',data=some_data)
json_dict = loads(result.text)
print([x["product_no"] for x in json_dict["list"]])
I am returning a JSON object from a requests call. I would like to get all the values from it and store them in a flat array.
My JSON object:
[
{
"link": "https://f.com/1"
},
{
"link": "https://f.com/2"
},
{
"link": "https://f.com/3"
}
]
I would like to store this as:
[https://f.com/things/1, https://f.com/things/2, https://f.com/things/3]
My code is as follows.. it is just printing each link out:
import requests
import json
def start_urls_data():
url = 'http://106309.n.com:3000/api/v1/product_urls?q%5Bcompany_in%5D%5B%5D=F'
headers = {'X-Api-Key': '1', 'Content-Type': 'application/json'}
r = requests.get(url, headers=headers)
start_urls_data = json.loads(r.content)
for i in start_urls_data:
print i['link']
You can use a simple list comprehension:
data = [
{
"link": "https://f.com/1"
},
{
"link": "https://f.com/2"
},
{
"link": "https://f.com/3"
}
]
print([x["link"] for x in data])
This code just loops through the list data and put the value of the key link from the dict element to a new list.