Related
I am integrating Paypal in django-rest- framework. The issue is with paypal webhook response. I get a webhook json response when ever I pay some amount on paypal already created a url path in my application for the same.
Sample JSON object response:
{'event_version': '1.0', 'create_time': '2022-12-19T18:57:12.343Z', 'resource_type': 'checkout-order', 'resource_version': '2.0', 'event_type': 'CHECKOUT.ORDER.APPROVED', 'summary': 'An order has been approved by buyer', 'resource': {'update_time': '2022-12-19T18:57:02Z', 'create_time': '2022-12-19T18:56:51Z', 'purchase_units': [{'reference_id': 'default', 'amount': {'currency_code': 'USD', 'value': '10.00'}, 'payee': {'email_address': 'mailto:sb-dgfcl23459178#business.example.com', 'merchant_id': ''jkdshfhsjdfhjksfhjsfs'}, 'custom_id': 'e-book-1234', 'shipping': {'name': {'full_name': 'John Doe'}, 'address': {'address_line_1': '1 Main St', 'admin_area_2': 'San Jose', 'admin_area_1': 'CA', 'postal_code': '95131', 'country_code': 'US'}}, 'payments': {'captures': [{'id': '9HW93194EE464044X', 'status': 'COMPLETED', 'amount': {'currency_code': 'USD', 'value': '10.00'}, 'final_capture': True, 'seller_protection': {'status': 'ELIGIBLE', 'dispute_categories': ['ITEM_NOT_RECEIVED', 'UNAUTHORIZED_TRANSACTION']}, 'seller_receivable_breakdown': {'gross_amount': {'currency_code': 'USD', 'value': '10.00'}, 'paypal_fee': {'currency_code': 'USD', 'value': '0.84'}, 'net_amount': {'currency_code': 'USD', 'value': '9.16'}}, 'links': [{'href': 'https://api.sandbox.paypal.com/v2/payments/captures/9HW93194EE464044X', 'rel': 'self', 'method': 'GET'}, {'href': 'https://api.sandbox.paypal.com/v2/payments/captures/9HW93194EE464044X/refund', 'rel': 'refund', 'method': 'POST'}, {'href': 'https://api.sandbox.paypal.com/v2/checkout/orders/4CV868937U646315D', 'rel': 'up', 'method': 'GET'}], 'create_time': '2022-12-19T18:57:02Z', 'update_time': '2022-12-19T18:57:02Z'}]}}], 'links': [{'href': 'https://api.sandbox.paypal.com/v2/checkout/orders/4CV868937U646315D', 'rel': 'self', 'method': 'GET'}], 'id': '4CV868937U646315D', 'payment_source': {'paypal': {}},
'intent': 'CAPTURE', 'payer': {'name': {'given_name': 'John', 'surname': 'Doe'},
'email_address': "adsfhjasdfhdajhk#gmail.com"
'payer_id': 'CSNQVZ49MMDA2',
'address': {'country_code': 'US'}},
'status': 'COMPLETED'},
'links': [{'href': 'https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-65K55150EC946744T-1T312384BP483891G', 'rel': 'self', 'method': 'GET'}, {'href': 'https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-65K55150EC946744T-1T312384BP483891G/resend', 'rel': 'resend', 'method': 'POST'}]}
Is there any inbuilt library which can handle this response in python or database design to handle this or I need to create it myself.
I am trying to load a text file formatted as JSON using the below code
with open('orderdata/ETHUSDTorder.txt') as json_file:
data = json.load(json_file)
actualdata=data['average']
print(actualdata)
print("read complete")
but it gives me below error
Traceback (most recent call last):
File "C:\Users\pavan.alur\PycharmProjects\pythonProject\main.py", line 30, in <module>
data = json.load(json_file)
File "C:\Users\pavan.alur\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\pavan.alur\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\pavan.alur\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\pavan.alur\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 2 column 5 (char 6)
Below is my text file
{
'info': {
'symbol': 'ETHUSD',
'orderid': '20556566',
'orderlistid': '-1',
'clientorderid': 'TXgguEidjfF9eLKF',
'transactiontime': '1619882734',
'price': '0.00',
'origqty': '0.00500',
'executedQty': '0.005000',
'commutativeQuoteQty': '143.06',
'status': 'Filled',
'timeInforce': 'GTC',
'type': 'MARKET',
'side': 'buy',
'fills': [{
'price': '2861.34',
'qty': '0.030',
'comission': '0.0001',
'comissionAsset': 'BNB',
'tradeid': '5722834'
}, {
'price': '2761.23',
'qty': '0.019',
'comission': '0.0001',
'comissionAsset': 'BNB',
'tradeid': '5722834'
}]
},
'id': '2044343',
'clientorderid': 'TXgguEidjfF9eLKF',
'timestamp': '1619882734',
'datetime': '2021-06-10T20:21:234',
'lasttradetimestamp': None,
'symbol': 'ETHUSD',
'type': 'MARKET',
'timeInforce': 'GTC',
'postonly': 'false',
'side': 'buy',
'price': '2861.23',
'stopprice': 'None',
'amount': 0.05,
'cost': 143.06,
'average': 2861.23,
'filled': 0.05,
'remaining': 0.0,
'status': 'closed',
'fee': {
'cost': 0.00013,
'currency': 'BNB'
},
'trades': [{
'info': {
'price': '2861.17',
'qty': '0.0330',
'comission': '0.0001',
'commissionAsset': 'BNB',
'tradeid': '2383487'
},
'timestamp': None,
'datetime': None,
'symbol': 'ETHUSD',
'id': None,
'order': None,
'type': None,
'side': None,
'takerOrMaker': None,
'price': 2861.23,
'amount': 0.034,
'cost': 87.534,
'fee': {
'cost': 0.0034,
'currency': 'BNB'
}
}, {
'info': {
'price': '2861.23',
'qty': '0.0019',
'comission': '0.0023',
'comissionAsset': 'BNB',
'tradeid': '453233'
},
'timestamp': None,
'datetime': None,
'symbol': 'ETHUSD',
'id': None,
'order': None,
'type': None,
'side': None,
'takerOrMaker': None,
'price': 2861.39,
'amount': 0.01941,
'cost': 55.53,
'fee': {
'cost': 6.737,
'currency': 'BNB'
}
}]
}
I am trying to get the "average" value and the JSON response is received from binance api
The response is received using ccxt library and I am trying to print the order that got executed and save the response in json format in text file Any help would be appreciated
I am a bit new to the python so please bear with me here
Thanks in advance. Have a great day :)
You need double-quotes for it to be valid JSON.
There are JSON validator and beautification web sites you can try.
jsonlint.com is one of them, for example.
I got it. Thanks, Ben for helping I just had to use dump to format everything and then load works perfectly. Silly me Thanks all for the help and have a great day ahead :)
I am pulling from an API in URL, and keep getting string indices must be integers error code thrown in python. I am wondering how to fix this? (The url is replaced with "url").
import urllib.request
import json
link = "url"
f = urllib.request.urlopen(link)
data = f.read()
print (str(data, 'utf-8'))
weather = json.loads(data)
print('/n')
print(weather["name"]["temp"])
Here's a sample of the json data:
{"coord":{"lon":-94.2166,"lat":36.4676},"weather":[{"id":600,"main":"Snow","description":"light snow","icon":"13n"}],"base":"stations","main":{"temp":262.83,"feels_like":255.36,"temp_min":262.04,"temp_max":263.71,"pressure":1025,"humidity":92},"visibility":10000,"wind":{"speed":6.17,"deg":30},"clouds":{"all":90},"dt":1613195709,"sys":{"type":1,"id":5695,"country":"US","sunrise":1613135272,"sunset":1613174070},"timezone":-21600,"id":0,"name":"Bella Vista","cod":200}
Here is the data snippet you shared formatted in a way that it makes it easier to see what is going on. As you can see, while weather["name"] is valid, weather["name"]["temp"] is not, and that is what is producing the error you are seeing. Instead, weather["main"]["temp"] will display the temperature value in that dictionary.
weather = {'base': 'stations',
'clouds': {'all': 90},
'cod': 200,
'coord': {'lat': 36.4676, 'lon': -94.2166},
'dt': 1613195709,
'id': 0,
'main': {'feels_like': 255.36,
'humidity': 92,
'pressure': 1025,
'temp': 262.83,
'temp_max': 263.71,
'temp_min': 262.04},
'name': 'Bella Vista',
'sys': {'country': 'US',
'id': 5695,
'sunrise': 1613135272,
'sunset': 1613174070,
'type': 1},
'timezone': -21600,
'visibility': 10000,
'weather': [{'description': 'light snow',
'icon': '13n',
'id': 600,
'main': 'Snow'}],
'wind': {'deg': 30, 'speed': 6.17}}
I have the following huge output from the code :urllib.request.urlopen("https://api...").read()
This looks like a JSON object but it is a bytes object. I am looking into on data into this whole. I am not sure how parse all these nested dictionary. Any help would be appreciated. I want to extract the value 112242287903649 located around the end.
b'{"address":"0x4264422fa4c1e60c2ee10d19549c0775fe544d7c","ETH":{"balance":39234.92760140797,"price":{"rate":406.0918669863694,"diff":3.33,"diff7d":7.19,"ts":1603860182,"marketCapUsd":45964513524.05101,"availableSupply":113187476.1865,"volume24h":14765115042.093159,"diff30d":14.028844201369225}},"countTxs":7,"tokens":[{"tokenInfo":{"address":"0x0d4b4da5fb1a7d55e85f8e22f728701ceb6e44c9","name":"DigiMax","decimals":"18","symbol":"DGMT","totalSupply":"1000000000000000000000000000","owner":"0x","lastUpdated":1603831313,"issuancesCount":0,"holdersCount":1042,"description":"DigiMax (DGMT) is a de-centralized Currency on ETHEREUM NETWORK. It is trustless, non-custodial, Layer-2 scaling solution for transferring value on Ethereum. It is Open Source. Community oriented and powered to maximize the power of the blockchain technology","website":"https://digimaxtoken.io/","twitter":"DigiMax_DGMT","image":"/images/DGMT0d4b4da5.png","telegram":"https://t.me/DigiMaxToken","reddit":"DigiMax_DGMT","coingecko":"digimax","price":{"rate":1.218303675e-5,"diff":3.55,"diff7d":-87.33,"ts":1603860187,"marketCapUsd":0,"availableSupply":0,"volume24h":0.36549128,"diff30d":-99.95948266499424,"currency":"USD"}},"balance":3.9e+19,"totalIn":0,"totalOut":0},{"tokenInfo":{"address":"0x28cb7e841ee97947a86b06fa4090c8451f64c0be","name":"YF Link","decimals":"18","symbol":"YFL","totalSupply":"52000000000000000000000","owner":"0x","lastUpdated":1603851830,"issuancesCount":0,"holdersCount":5164,"image":"/images/YFL28cb7e84.png","website":"https://yflink.io/","telegram":"https://t.me/YFLinkGroup","twitter":"YFLinkio","coingecko":"yflink","price":{"rate":411.62315709142763,"diff":2.44,"diff7d":22.67,"ts":1603860243,"marketCapUsd":20628385.985420085,"availableSupply":50114.73633112,"volume24h":673808.77973096,"diff30d":-9.745291974110742,"currency":"USD"},"publicTags":["Yield Farming","Yearn","Governance"]},"balance":69000000000000,"totalIn":0,"totalOut":0},{"tokenInfo":{"address":"0x618e75ac90b12c6049ba3b27f5d5f8651b0037f6","name":"QASH","decimals":"6","symbol":"QASH","totalSupply":"1000000000000000","owner":"0x9fa8a9cd0bd7cbfc503513bc94cd3b3a9ca90e35","lastUpdated":1603818056,"issuancesCount":0,"holdersCount":13087,"website":"https://liquid.plus/","facebook":"LiquidGlobal","telegram":"https://t.me/QUOINENews","twitter":"Liquid_Global","image":"/images/QASH618e75ac.jpeg","reddit":"liquid","coingecko":"qash","ethTransfersCount":2,"price":{"rate":0.03783789848158,"diff":2.83,"diff7d":0.05,"ts":1603860243,"marketCapUsd":13243264.468553,"availableSupply":350000000,"volume24h":170565.95092274,"diff30d":-5.421371004476654,"currency":"USD"},"publicTags":["Exchange"]},"balance":112242287903649,"totalIn":0,"totalOut":0},{"tokenInfo":{"address":"0x9f7229af0c4b9740e207ea283b9094983f78ba04","decimals":"18","name":"Tadpole","owner":"0x","symbol":"TAD","totalSupply":"1000000000000000000000000","lastUpdated":1603859098,"issuancesCount":0,"holdersCount":597,"price":false},"balance":100000000000000,"totalIn":0,"totalOut":0}]}'
The in built json module is perfectly capable of parsing byte strings-
import json
response = urllib.request.urlopen("https://api/endpoint").read()
jsondat = json.loads(response)
Now you can use jsondat however you'd like and extract whichever nested property you desire.
Note that you can also use the requests module, though you absolutely don't have to in this case, to achieve this a bit more simply-
import requests
jsondat = requests.get("https://api/endpoint").json()
Doing json.loads on your given byte string yields-
{'address': '0x4264422fa4c1e60c2ee10d19549c0775fe544d7c',
'ETH': {'balance': 39234.92760140797,
'price': {'rate': 406.0918669863694,
'diff': 3.33,
'diff7d': 7.19,
'ts': 1603860182,
'marketCapUsd': 45964513524.05101,
'availableSupply': 113187476.1865,
'volume24h': 14765115042.093159,
'diff30d': 14.028844201369225}},
'countTxs': 7,
'tokens': [{'tokenInfo': {'address': '0x0d4b4da5fb1a7d55e85f8e22f728701ceb6e44c9',
'name': 'DigiMax',
'decimals': '18',
'symbol': 'DGMT',
'totalSupply': '1000000000000000000000000000',
'owner': '0x',
'lastUpdated': 1603831313,
'issuancesCount': 0,
'holdersCount': 1042,
'description': 'DigiMax (DGMT) is a de-centralized Currency on ETHEREUM NETWORK. It is trustless, non-custodial, Layer-2 scaling solution for transferring value on Ethereum. It is Open Source. Community oriented and powered to maximize the power of the blockchain technology',
'website': 'https://digimaxtoken.io/',
'twitter': 'DigiMax_DGMT',
'image': '/images/DGMT0d4b4da5.png',
'telegram': 'https://t.me/DigiMaxToken',
'reddit': 'DigiMax_DGMT',
'coingecko': 'digimax',
'price': {'rate': 1.218303675e-05,
'diff': 3.55,
'diff7d': -87.33,
'ts': 1603860187,
'marketCapUsd': 0,
'availableSupply': 0,
'volume24h': 0.36549128,
'diff30d': -99.95948266499424,
'currency': 'USD'}},
'balance': 3.9e+19,
'totalIn': 0,
'totalOut': 0},
{'tokenInfo': {'address': '0x28cb7e841ee97947a86b06fa4090c8451f64c0be',
'name': 'YF Link',
'decimals': '18',
'symbol': 'YFL',
'totalSupply': '52000000000000000000000',
'owner': '0x',
'lastUpdated': 1603851830,
'issuancesCount': 0,
'holdersCount': 5164,
'image': '/images/YFL28cb7e84.png',
'website': 'https://yflink.io/',
'telegram': 'https://t.me/YFLinkGroup',
'twitter': 'YFLinkio',
'coingecko': 'yflink',
'price': {'rate': 411.62315709142763,
'diff': 2.44,
'diff7d': 22.67,
'ts': 1603860243,
'marketCapUsd': 20628385.985420085,
'availableSupply': 50114.73633112,
'volume24h': 673808.77973096,
'diff30d': -9.745291974110742,
'currency': 'USD'},
'publicTags': ['Yield Farming', 'Yearn', 'Governance']},
'balance': 69000000000000,
'totalIn': 0,
'totalOut': 0},
{'tokenInfo': {'address': '0x618e75ac90b12c6049ba3b27f5d5f8651b0037f6',
'name': 'QASH',
'decimals': '6',
'symbol': 'QASH',
'totalSupply': '1000000000000000',
'owner': '0x9fa8a9cd0bd7cbfc503513bc94cd3b3a9ca90e35',
'lastUpdated': 1603818056,
'issuancesCount': 0,
'holdersCount': 13087,
'website': 'https://liquid.plus/',
'facebook': 'LiquidGlobal',
'telegram': 'https://t.me/QUOINENews',
'twitter': 'Liquid_Global',
'image': '/images/QASH618e75ac.jpeg',
'reddit': 'liquid',
'coingecko': 'qash',
'ethTransfersCount': 2,
'price': {'rate': 0.03783789848158,
'diff': 2.83,
'diff7d': 0.05,
'ts': 1603860243,
'marketCapUsd': 13243264.468553,
'availableSupply': 350000000,
'volume24h': 170565.95092274,
'diff30d': -5.421371004476654,
'currency': 'USD'},
'publicTags': ['Exchange']},
'balance': 112242287903649,
'totalIn': 0,
'totalOut': 0},
{'tokenInfo': {'address': '0x9f7229af0c4b9740e207ea283b9094983f78ba04',
'decimals': '18',
'name': 'Tadpole',
'owner': '0x',
'symbol': 'TAD',
'totalSupply': '1000000000000000000000000',
'lastUpdated': 1603859098,
'issuancesCount': 0,
'holdersCount': 597,
'price': False},
'balance': 100000000000000,
'totalIn': 0,
'totalOut': 0}]}
I have tried to find the answer but I could not find it
I am looking for the way to save in my computer a json file from python.
I call the API
configuration = api.Configuration()
configuration.api_key['X-XXXX-Application-ID'] = 'xxxxxxx'
configuration.api_key['X-XXX-Application-Key'] = 'xxxxxxxx1'
## List our parameters as search operators
opts= {
'title': 'Deutsche Bank',
'body': 'fraud',
'language': ['en'],
'published_at_start': 'NOW-7DAYS',
'published_at_end': 'NOW',
'per_page': 1,
'sort_by': 'relevance'
}
try:
## Make a call to the Stories endpoint for stories that meet the criteria of the search operators
api_response = api_instance.list_stories(**opts)
## Print the returned story
pp(api_response.stories)
except ApiException as e:
print('Exception when calling DefaultApi->list_stories: %s\n' % e)
I got the response like this
[{'author': {'avatar_url': None, 'id': 1688440, 'name': 'Pranav Nair'},
'body': 'The law firm will investigate whether the bank or its officials have '
'engaged in securities fraud or unlawful business practices. '
'Industries: Bank Referenced Companies: Deutsche Bank',
'categories': [{'confident': False,
'id': 'IAB11-5',
'level': 2,
'links': {'_self': 'https://,
'parent': 'https://'},
'score': 0.39,
'taxonomy': 'iab-qag'},
{'confident': False,
'id': 'IAB3-12',
'level': 2,
'links': {'_self': 'https://api/v1/classify/taxonomy/iab-qag/IAB3-12',
'score': 0.16,
'taxonomy': 'iab-qag'},
'clusters': [],
'entities': {'body': [{'indices': [[168, 180]],
'links': {'dbpedia': 'http://dbpedia.org/resource/Deutsche_Bank'},
'score': 1.0,
'text': 'Deutsche Bank',
'types': ['Bank',
'Organisation',
'Company',
'Banking',
'Agent']},
{'indices': [[80, 95]],
'links': {'dbpedia': 'http://dbpedia.org/resource/Securities_fraud'},
'score': 1.0,
'text': 'securities fraud',
'types': ['Practice', 'Company']},
'hashtags': ['#DeutscheBank', '#Bank', '#SecuritiesFraud'],
'id': 3004661328,
'keywords': ['Deutsche',
'behalf',
'Bank',
'firm',
'investors',
'Deutsche Bank',
'bank',
'fraud',
'unlawful'],
'language': 'en',
'links': {'canonical': None,
'coverages': '/coverages?story_id=3004661328',
'permalink': 'https://www.snl.com/interactivex/article.aspx?KPLT=7&id=58657069',
'related_stories': '/related_stories?story_id=3004661328'},
'media': [],
'paragraphs_count': 1,
'published_at': datetime.datetime(2020, 5, 19, 16, 8, 5, tzinfo=tzutc()),
'sentences_count': 2,
'sentiment': {'body': {'polarity': 'positive', 'score': 0.599704},
'title': {'polarity': 'neutral', 'score': 0.841333}},
'social_shares_count': {'facebook': [],
'google_plus': [],
'source': {'description': None,
'domain': 'snl.com',
'home_page_url': 'http://www.snl.com/',
'id': 8256,
'links_in_count': None,
'locations': [{'city': 'Charlottesville',
'country': 'US',
'state': 'Virginia'}],
'logo_url': None,
'name': 'SNL Financial',
'scopes': [{'city': None,
'country': 'US',
'level': 'national',
'state': None},
{'city': None,
'country': None,
'level': 'international',
'state': None}],
'title': None},
'summary': {'sentences': ['The law firm will investigate whether the bank or '
'its officials have engaged in securities fraud or '
'unlawful business practices.',
'Industries: Bank Referenced Companies: Deutsche '
'Bank']},
'title': "Law firm to investigate Deutsche Bank's US ops on behalf of "
'investors',
'translations': {'en': None},
'words_count': 26}]
In the documentation says "Stories you retrieve from the API are returned as JSON objects by default. These JSON story objects contain 22 top-level fields, whereas a full story object will contain 95 unique data points"
The class is a list. When I have tried to save json file I have the error "TypeError: Object of type Story is not JSON serializable".
How I can save a json file in my computer?
The response you got is not json, json uses double quotes, but here its single quotes. Copy paste your response in the following link to see the issues
http://json.parser.online.fr/.
If you change it like
[{"author": {"avatar_url": None, "id": 1688440, "name": "Pranav Nair"},
"body": "......
It will work, You can use python json module to do it
import json
json.loads(the_dict_got_from_response).
But it should be the duty of the API provider to, To make it working you can json load the result you got.