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.
Related
I'm wanting to do a put in an API where I will receive data from an excel spreadsheet.
Here's my python code:
for s, Id in enumerate(spreed_sheet["itemId"]):
mark = str(spreed_sheet.loc[s,"markup"])
prod_price = str(float(spreed_sheet.loc[s, "listPrice"]))
prod_base = str(float(spreed_sheet.loc[s, "basePrice"]))
prod_cost = str(int(spreed_sheet.loc[s, "costPrice"]))
policy_produ = str(int(spreed_sheet.loc[s,"tradePolicyId"]))
prod_value = str(float(spreed_sheet.loc[s, "value"]))
fixed_list = str(int(spreed_sheet.loc[s, "listPrice"]))
min_qt = str(int(spreed_sheet.loc[s, "minQuantity"]))
date_from = str(spreed_sheet.loc[s, "from"])
date_to = str(spreed_sheet.loc[s, "to"])
payloads = {"itemId": Id, "markup": mark, "listPrice": prod_price, "basePrice": prod_base, "costPrice": prod_cost, "tradePolicyId": policy_produ, "value": prod_value, "listPrice": fixed_list, "minQuantity": min_qt, "from": date_from, "to": date_to}
url = f"https://myapi/myaccountname/pricing/prices/{Id}"
response = requests.put(url, headers=headers, json=payloads)
print(response.text)
response = response.json()
I change the name of account name for "myaccountname", in my code the name is there. But, when I try to pass the excel file for the api I get the follow error:
[Errno Expecting value] A JSON parsing error has occurred: json: cannot unmarshal number into Go struct field PutPriceRequest.itemId of type string : 0
The API call actually has two listPrice. The response body would look like this:
{
"markup": 30,
"basePrice": 100,
"listPrice": 12,
"costPrice": 40,
"fixedPrices": [
{
"tradePolicyId": "1",
"value": 2.99,
"listPrice": 1,
"minQuantity": 1,
"dateRange": {
"from": "2020-05-21T22:00:00Z",
"to": "2020-05-28T22:00:00Z"
}
},
{
"tradePolicyId": "1",
"value": 0.49,
"listPrice": null,
"minQuantity": 2
}
]
}
How can I resolve this error?
Edit after making the changes
payloads = {"markup": mark, "listPrice": prod_price, "basePrice": prod_base, "costPrice": prod_cost, "tradePolicyId": policy_produ, "value": prod_value, "listPrice": fixed_list, "minQuantity": min_qt, "from": date_from, "to": date_to}
The error message is telling you that the type of value received for itemId is not correct.
You've called the API with a number as the itemId field, but the API is expecting a string.
So you could modify that part of the code to:
payloads = {"itemId": str(Id), ...
You should look at the API specification to see what types are being expected for the payload items. You're converting all of the other data items to a string, but it's unlikely that the API is expecting everything to be strings.
resp = {
"Name": "test",
"os": "windows",
"Agent": {
"id": "2",
"status": [
{
"code": "123",
"level": "Info",
"displayStatus": "Ready",
"message": "running",
"time": "2022-01-18T09:51:08+00:00"
}
]
}
I am trying to get the time value from the JSON.
I tried the below code but faced error with dict
resp1 = json.loads(resp)
resp2 = resp1.values()
creation_time = resp2.get("Agent").get("status")
val= creation_time["time"]
print(val) ## Thrwoing error as dict_values has no 'get'
Any suggestion on python how to take this time values
Few problems I noticed
You are trying to load a Dict type using the json's loads function which is supposed to get a string in json format (ex: '{ "name":"John", "age":30, "city":"New York"}')
You tried to access resp2 before declaration (I guessed you meant "resp1?")
You're using resp3 without declaration.
You are missing }
You don't need the .value() function because it will return a list.
Also creation time is a list with one object, so you need to access it too.
Considering all this, you can change it as follows:
import json
resp = '{ "Name": "test", "os": "windows","Agent": {"id": "2","status": [{"code": "123","level": "Info","displayStatus": "Ready","message": "running","time": "2022-01-18T09:51:08+00:00"}]}}'
resp1 = json.loads(resp)
creation_time = resp1.get("Agent").get("status")
val= creation_time[0]["time"]
print(val)
You just need to access the dicts using [] like so:
resp = {"Name": "test", "os": "windows", "Agent": {"id": "2","status": [{"code": "123","level": "Info","displayStatus": "Ready","message": "running","time": "2022-01-18T09:51:08+00:00"}]}}
creation_time = resp["Agent"]["status"]
val= creation_time[0]["time"]
print(val)
Output:
2022-01-18T09:51:08+00:00
I am using python 3.6.3a. I would like to generate payload for each of the json records. I am using each variable to access the record. How to assign variable value (each in this case) in payload? I tried {each} and other methods but didn't work.
code snippet below.
json_records = [{"description":"<p>This is scenario1<\/p>","owner":"deb",
"priority":"high"},
{"description":"<p>This is scenario2<\/p>","owner":"deb",
"priority":"medium"}]
json_object = json.loads(json_records)
for each in json_object:
payload = """
{
"subject": "test",
"fieldValues": [
{each}
]
}
"""
There are two ways to approach this problem.
One way could be creating a dict() object and inserting keys as you wish, then json.dumps(object) to convert into string payload as in:
import json
json_records = [{"description":"This is scenario1</p>","owner":"deb","priority":"high"}
,{"description":"This is scenario2</p>","owner":"deb","priority":"medium"}]
for obj in json_records:
payload = dict()
payload['subject'] = 'test'
for key,value in obj.items():
payload['fieldName'] = {
key:value
}
print(json.dumps(payload))
#{"subject": "test", "fieldName": {"priority": "high"}}
#{"subject": "test", "fieldName": {"priority": "medium"}}
Second way is to create a textual payload from string as in, however if you need a valid JSON at the end, this would require a post-step of validation (something like try json.loads(payload) - So I'd just use the first method. I would use this method only if I have a specific requirements to generate the payload in a certain way.
import json
json_records = [{"description":"This is scenario1</p>","owner":"deb","priority":"high"}
,{"description":"This is scenario2</p>","owner":"deb","priority":"medium"}]
# json_object = json.loads(json_records) # json.loads works only on byte-like strings. your object is already in python in this case.
for obj in json_records:
payload = """
{
"subject": "test",
"fieldValues": [
%s
]
}
""" % (obj["priority"])
print(payload)
#{
# "subject": "test",
# "fieldValues": [
# high
# ]
# }
#
#
# {
# "subject": "test",
# "fieldValues": [
# medium
# ]
# }
You could make payload a Template string and use it to put the data in each JSON record into the format you want. Bracket {} characters have not special meaning in Templates, which is what makes using them easy.
Doing that will create a valid string representation of a dictionary containing everything. You can turn this into an actual Python dictionary data-structure using the ast.literal_eval() function, and then convert that into JSON string format — which I think is the final format you're after.
rom ast import literal_eval
import json
from string import Template
from textwrap import dedent
json_records = '''[{"description":"<p>This is scenario1<\/p>","owner":"deb",
"priority":"high"},
{"description":"<p>This is scenario2<\/p>","owner":"deb",
"priority":"medium"}]'''
json_object = json.loads(json_records)
payload = Template(dedent("""
{
"subject": "test",
"fieldValues": [
$each
]
}""")
)
for each in json_object:
obj = literal_eval(payload.substitute(dict(each=each)))
print(json.dumps(obj, indent=2))
Output:
{
"subject": "test",
"fieldValues": [
{
"description": "<p>This is scenario1</p>",
"owner": "deb",
"priority": "high"
}
]
}
{
"subject": "test",
"fieldValues": [
{
"description": "<p>This is scenario2</p>",
"owner": "deb",
"priority": "medium"
}
]
}
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'])
I'm using the following python code to connect to a jsonrpc server and nick some song information. However, I can't work out how to get the current title in to a variable to print elsewhere. Here is the code:
TracksInfo = []
for song in playingSongs:
data = { "id":1,
"method":"slim.request",
"params":[ "",
["songinfo",0,100, "track_id:%s" % song, "tags:GPASIediqtymkovrfijnCYXRTIuwxN"]
]
}
params = json.dumps(data, sort_keys=True, indent=4)
conn.request("POST", "/jsonrpc.js", params)
httpResponse = conn.getresponse()
data = httpResponse.read()
responce = json.loads(data)
print json.dumps(responce, sort_keys=True, indent=4)
TrackInfo = responce['result']["songinfo_loop"][0]
TracksInfo.append(TrackInfo)
This brings me back the data in json format and the print json.dump brings back:
pi#raspberrypi ~/pithon $ sudo python tom3.py
{
"id": 1,
"method": "slim.request",
"params": [
"",
[
"songinfo",
"0",
100,
"track_id:-140501481178464",
"tags:GPASIediqtymkovrfijnCYXRTIuwxN"
]
],
"result": {
"songinfo_loop": [
{
"id": "-140501481178464"
},
{
"title": "Witchcraft"
},
{
"artist": "Pendulum"
},
{
"duration": "253"
},
{
"tracknum": "1"
},
{
"type": "Ogg Vorbis (Spotify)"
},
{
"bitrate": "320k VBR"
},
{
"coverart": "0"
},
{
"url": "spotify:track:2A7ZZ1tjaluKYMlT3ItSfN"
},
{
"remote": 1
}
]
}
}
What i'm trying to get is result.songinfoloop.title (but I tried that!)
The songinfo_loop structure is.. peculiar. It is a list of dictionaries each with just one key.
Loop through it until you have one with a title:
TrackInfo = next(d['title'] for d in responce['result']["songinfo_loop"] if 'title' in d)
TracksInfo.append(TrackInfo)
A better option would be to 'collapse' all those dictionaries into one:
songinfo = reduce(lambda d, p: d.update(p) or d,
responce['result']["songinfo_loop"], {})
TracksInfo.append(songinfo['title'])
songinfo_loop is a list not a dict. That means you need to call it by position, or loop through it and find the dict with a key value of "title"
positional:
responce["result"]["songinfo_loop"][1]["title"]
loop:
for info in responce["result"]["songinfo_loop"]:
if "title" in info.keys():
print info["title"]
break
else:
print "no song title found"
Really, it seems like you would want to have the songinfo_loop be a dict, not a list. But if you need to leave it as a list, this is how you would pull the title.
The result is really a standard python dict, so you can use
responce["result"]["songinfoloop"]["title"]
which should work