Parse urlib request - python

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}]}

Related

PayPal webhooks integration with django

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.

Trying to get key value as a column in a table from JSON

Python noob here. I have a dictionary being created with a for loop API call. I'm getting the data back fine, but now I need to create a table from it, with the first column being the key(zip code).
results = dict()
for each_zip in all_zips_dedup:
r = requests.get('http://api.openweathermap.org/data/2.5/weather?zip=' + str(each_zip) + ',' + country_code + '&units=imperial' + '&appid=' + api_key)
data = json.loads(r.text)
results.update({each_zip: data})
Example of first record of dictionary:
{92064: {'coord': {'lon': -117.04, 'lat': 32.98}, 'weather': [{'id': 800, 'main': 'Clear', 'description': 'clear sky', 'icon': '01d'}], 'base': 'stations', 'main': {'temp': 69.66, 'feels_like': 64.33, 'temp_min': 66.2, 'temp_max': 72, 'pressure': 1019, 'humidity': 22}, 'visibility': 10000, 'wind': {'speed': 2.39, 'deg': 106}, 'clouds': {'all': 1}, 'dt': 1606932174, 'sys': {'type': 1, 'id': 5686, 'country': 'US', 'sunrise': 1606919677, 'sunset': 1606956087}, 'timezone': -28800, 'id': 0, 'name': 'Poway', 'cod': 200},...
I guess I have 2 troubles with this:
How do I get a table saved to csv from my JSON with a column containing the key values?
How can I get one column for different desired levels within the dictionary (i.e. - for 'weather' I would just want a column for 'id','main','description','icon')
I'm probably just in way over my head, but I really appreciate any help!
When you post, please don't post images, post actual data. It's not clear what your asking in Q1. If you have data and can parse into a pandas dataframe, you can use pandas.to_csv to write to excel. there are other libraries that can help as well.
However, import into pandas doesn't give a straightforward parsing.
import pandas as pd
results = {92064: {'coord': {'lon': -117.04, 'lat': 32.98}, 'weather': [{'id': 800, 'main': 'Clear', 'description': 'clear sky', 'icon': '01d'}], 'base': 'stations', 'main': {'temp': 69.66, 'feels_like': 64.33, 'temp_min': 66.2, 'temp_max': 72, 'pressure': 1019, 'humidity': 22}, 'visibility': 10000, 'wind': {'speed': 2.39, 'deg': 106}, 'clouds': {'all': 1}, 'dt': 1606932174, 'sys': {'type': 1, 'id': 5686, 'country': 'US', 'sunrise': 1606919677, 'sunset': 1606956087}, 'timezone': -28800, 'id': 0, 'name': 'Poway', 'cod': 200}}
df = pd.DataFrame(results).T # T is to transpose the data
df.to_csv('filename.csv') # there are other options when writing csv files so check out the pandas docs
to get further down the chain you can do this:
results[92064]['weather']
In [138]: results[92064]['weather']
Out[138]: [{'id': 800, 'main': 'Clear', 'description': 'clear sky', 'icon': '01d'}]
In [141]: pd.DataFrame(results[92064]['weather'])
Out[141]:
id main description icon
0 800 Clear clear sky 01d

General Python Question - how to unwind scrambled data

I'm a novice in Python and I'm having trouble with reading the API content and then looking in which dictionary and which list the information I want is in, etc. Is there an easier way than printing out elements down until you find the piece of data you want?
For example. I am trying to get to this element {'name': 'Famagusta District', 'lang': 'en'}
From this monstrosity:
{'address': 'Ammochostos', 'bbox': [33.548065185546875, 34.959442138671875, 34.590553283691406, 35.690277099609375], 'class_description': 'country, state, region,...', 'code': 'ADM1', 'confidence': 1, 'continent': 'EU', 'country': 'Cyprus', 'country_code': 'CY', 'country_geonames_id': '146669', 'description': 'first-order administrative division', 'dstOffset': 3, 'feature_class': 'A', 'geonames_id': 146615, 'lat': '35.33333', 'lng': '33.86667', 'ok': True, 'population': 46629, 'raw': {'timezone': {'gmtOffset': 2, 'timeZoneId': 'Asia/Famagusta', 'dstOffset': 3}, 'bbox': {'east': 34.590553283691406, 'south': 34.959442138671875, 'north': 35.690277099609375, 'west': 33.548065185546875, 'accuracyLevel': 0}, 'asciiName': 'Eparchia Ammochostou', 'astergdem': 133, 'countryId': '146669', 'fcl': 'A', 'srtm3': 134, 'countryCode': 'CY', 'adminCodes1': {'ISO3166_2': '04'}, 'adminId1': '146615', 'lat': '35.33333', 'fcode': 'ADM1', 'continentCode': 'EU', 'adminCode1': '01', 'lng': '33.86667', 'geonameId': 146615, 'toponymName': 'Eparchía Ammochóstou', 'adminTypeName': 'district', 'population': 46629, 'wikipediaURL': 'en.wikipedia.org/wiki/Famagusta_District', 'adminName5': '', 'adminName4': '', 'adminName3': '', 'alternateNames': [{'isPreferredName': True, 'name': '파마구스타 구', 'lang': 'ko'}, {'isShortName': True, 'isPreferredName': True, 'name': 'Ammochostos', 'lang': 'en'}, {'name': 'Ammóchostos', 'lang': 'el'}, {'name': 'Ammochostos District', 'lang': 'en'}, {'name': 'Eparchía Ammochóstou'}, {'name': 'Famagouste', 'lang': 'fr'}, {'isShortName': True, 'name': 'Famagusta', 'lang': 'en'}, {'name': 'Famagusta District', 'lang': 'en'}, {'name': 'Gazi Magosa İlçesi', 'lang': 'tr'}, {'name': 'Gazimağusa', 'lang': 'tr'}, {'name': 'https://en.wikipedia.org/wiki/Famagusta_District', 'lang': 'link'}, {'name': 'Magosa İlçesi', 'lang': 'tr'}, {'name': 'Q59148', 'lang': 'wkdt'}, {'name': 'Αμμόχωστος', 'lang': 'el'}, {'isPreferredName': True, 'name': 'Επαρχία Αμμοχώστου', 'lang': 'el'}], 'adminName2': '', 'name': 'Ammochostos', 'fclName': 'country, state, region,...', 'countryName': 'Cyprus', 'fcodeName': 'first-order administrative division', 'adminName1': 'Ammochostos'}, 'rawOffset': 2, 'srtm3': 134, 'state': 'Ammochostos', 'state_code': '01', 'state_geonames_id': '146615', 'status': 'OK', 'timeZoneId': 'Asia/Famagusta', 'timeZoneName': 'Asia/Famagusta', 'wikipedia': 'en.wikipedia.org/wiki/Famagusta_District'}
So Far I went so already 3 levels down but 4th layer seems to have at least dozen elements and AlternateNames is not one of them so it's at least 1 more level down.
print(row['features'][0]['properties'])
I am using Pycharm. Is there any way to view this with indentation or search function? If not what is the easiest way to read the elements down?
I'm not sure what name you have given to your dictionary. I have copied the text above and assigned it to a dictionary called 'dict1' for the purposes of showing you this answer.
dict1 = {'address': 'Ammochostos', 'bbox': [33.548065185546875, 34.959442138671875, 34.590553283691406, 35.690277099609375], 'class_description': 'country, state, region,...', 'code': 'ADM1', 'confidence': 1, 'continent': 'EU', 'country': 'Cyprus', 'country_code': 'CY', 'country_geonames_id': '146669', 'description': 'first-order administrative division', 'dstOffset': 3, 'feature_class': 'A', 'geonames_id': 146615, 'lat': '35.33333', 'lng': '33.86667', 'ok': True, 'population': 46629, 'raw': {'timezone': {'gmtOffset': 2, 'timeZoneId': 'Asia/Famagusta', 'dstOffset': 3}, 'bbox': {'east': 34.590553283691406, 'south': 34.959442138671875, 'north': 35.690277099609375, 'west': 33.548065185546875, 'accuracyLevel': 0}, 'asciiName': 'Eparchia Ammochostou', 'astergdem': 133, 'countryId': '146669', 'fcl': 'A', 'srtm3': 134, 'countryCode': 'CY', 'adminCodes1': {'ISO3166_2': '04'}, 'adminId1': '146615', 'lat': '35.33333', 'fcode': 'ADM1', 'continentCode': 'EU', 'adminCode1': '01', 'lng': '33.86667', 'geonameId': 146615, 'toponymName': 'Eparchía Ammochóstou', 'adminTypeName': 'district', 'population': 46629, 'wikipediaURL': 'en.wikipedia.org/wiki/Famagusta_District', 'adminName5': '', 'adminName4': '', 'adminName3': '', 'alternateNames': [{'isPreferredName': True, 'name': '파마구스타 구', 'lang': 'ko'}, {'isShortName': True, 'isPreferredName': True, 'name': 'Ammochostos', 'lang': 'en'}, {'name': 'Ammóchostos', 'lang': 'el'}, {'name': 'Ammochostos District', 'lang': 'en'}, {'name': 'Eparchía Ammochóstou'}, {'name': 'Famagouste', 'lang': 'fr'}, {'isShortName': True, 'name': 'Famagusta', 'lang': 'en'}, {'name': 'Famagusta District', 'lang': 'en'}, {'name': 'Gazi Magosa İlçesi', 'lang': 'tr'}, {'name': 'Gazimağusa', 'lang': 'tr'}, {'name': 'https://en.wikipedia.org/wiki/Famagusta_District', 'lang': 'link'}, {'name': 'Magosa İlçesi', 'lang': 'tr'}, {'name': 'Q59148', 'lang': 'wkdt'}, {'name': 'Αμμόχωστος', 'lang': 'el'}, {'isPreferredName': True, 'name': 'Επαρχία Αμμοχώστου', 'lang': 'el'}], 'adminName2': '', 'name': 'Ammochostos', 'fclName': 'country, state, region,...', 'countryName': 'Cyprus', 'fcodeName': 'first-order administrative division', 'adminName1': 'Ammochostos'}, 'rawOffset': 2, 'srtm3': 134, 'state': 'Ammochostos', 'state_code': '01', 'state_geonames_id': '146615', 'status': 'OK', 'timeZoneId': 'Asia/Famagusta', 'timeZoneName': 'Asia/Famagusta', 'wikipedia': 'en.wikipedia.org/wiki/Famagusta_District'}
Running dict1 alone will allow you to view how this looks in a much neater way. (I'm using Google Colab)
If I then run this line, it returns the data you are interested in:
dict1['raw']['alternateNames'][7]
This works because you must return the elements within the outer dictionary, and inner dictionaries. Once you reach 'alternateNames', you can find the information you want using list indexing.

How do I turn my JSON into something easier to read?

My Python script connects to an API and gets some JSON.
I've been trying out prettyprint, parse, loads, dumps but I haven't figured them out yet...
Right now, when i do print(request.json()) I get this:
{'info': {'status': 'OK', 'time': {'seconds': 0.050006151199341, 'human': '50 milliseconds'}},
'datalist': {'total': 1, 'count': 1, 'offset': 0, 'limit': 3, 'next': 1, 'hidden': 0, 'loaded': True, 'list': [
{'id': 27862209, 'name': 'Fate/Grand Order', 'package': 'com.xiaomeng.fategrandorder',
'uname': 'komoe-game-fate-go', 'size': 49527668,
'icon': 'http://pool.img.xxxxx.com/msi8/9b58a48638b480c17135a10810374bd6_icon.png',
'graphic': 'http://pool.img.xxxxx.com/msi8/3a240b50ac37a9824b9ac99f1daab8c8_fgraphic_705x345.jpg',
'added': '2017-05-20 10:54:53', 'modified': '2017-05-20 10:54:53', 'updated': '2018-02-12 12:35:51',
'uptype': 'regular', 'store': {'id': 750918, 'name': 'msi8',
'avatar': 'http://pool.img.xxxxx.com/msi8/c61a8cfe9f68bfcfb71ef59b46a8ae5d_ravatar.png',
'appearance': {'theme': 'grey',
'description': '❤️ Welcome To Msi8 Store & My Store Will Mostly Be Specialized in Games With OBB File Extension. I Hope You Find What You Are Looking For Here ❤️'},
'stats': {'apps': 20776, 'subscribers': 96868, 'downloads': 25958359}},
'file': {'vername': '1.14.5', 'vercode': 52, 'md5sum': 'xxxxx', 'filesize': 49527668,
'path': 'http://pool.apk.xxxxx.com/msi8/com-xiaomeng-fategrandorder-52-27862209-32a264b031d6933514970c43dea4191f.apk',
'path_alt': 'http://pool.apk.xxxxx.com/msi8/alt/Y29tLXhpYW9tZW5nLWZhdGVncmFuZG9yZGVyLTUyLTI3ODYyMjA5LTMyYTI2NGIwMzFkNjkzMzUxNDk3MGM0M2RlYTQxOTFm.apk',
'malware': {'rank': 'UNKNOWN'}},
'stats': {'downloads': 432, 'pdownloads': 452, 'rating': {'avg': 0, 'total': 0},
'prating': {'avg': 0, 'total': 0}}, 'has_versions': False, 'obb': None,
'xxxxx': {'advertising': False, 'billing': False}}]}}
But I want it to look like this:
>>> import json
>>> a={"some":"json", "a":{"b":[1,2,3,4]}}
>>> print(json.dumps(a, indent=4, sort_keys=True))
{
"a": {
"b": [
1,
2,
3,
4
]
},
"some": "json"
}

GDAX api, dictionaries and request class

I am a complete novice at Python but have coded basic things in the past. I a looking to code some relatively simple trailing stop loss code. I am using the GDAX docs and the guide at Cryptostag and have managed to get some of it working. I think I should be ok with the actual algorithm to place orders at the right time but need help with the api and extracting information.
Problem 1:
`lorder = requests.get(api_base + '/orders/' + 'f39d35ec-ba7e-49ed-a21e-d78a8168907c', auth=auth)
print (lorder.json())`
This results in {'message': 'invalid signature'}. But I can't think why.
Problem 2:
accts = requests.get(api_base + 'accounts', auth=auth)
Returns
[{'id': '16d672da-b3eb-4e42-bfc2-da0c8e788fa8', 'currency': 'LTC', 'balance': '0.1234567000000000', 'available': '0.2931758', 'hold': '0.6000000000000000', 'profile_id': '172f7b0b-16b2-3b81-a92f-b7ac1ad253df'}, {'id': '430025c7-0109-4167-739c-15324cfabd8c', 'currency': 'EUR', 'balance': '120.6713649805422500', 'available': '012.14336468054225', 'hold': '324.5280000000000000', 'profile_id': '373f8b0b-18b2-4b71-a91f-b9ac6ad243df'}, {'id': '53d4403f-ea07-47c9-87dd-fa3bf887a5a2', 'currency': 'BTC', 'balance': '0.0087190400000000', 'available': '0.00871904', 'hold': '0.0000000000000000', 'profile_id': '172f7b0b-16b2-3b81-a92f-b7ac1ad253df'}, {'id': '1a25b6a9-90cd-4205-ac18-960cd6e1e50e', 'currency': 'GBP', 'balance': '0.0000000000000000', 'available': '0', 'hold': '0.0000000000000000', 'profile_id': '172f7b0b-16b2-3b81-a92f-b7ac1ad253df'}, {'id': '35470e2c-de36-93ea-8716-c35c34bg92e7', 'currency': 'ETH', 'balance': '0.6582615200000000', 'available': '0.50886152', 'hold': '0.1600000000000000', 'profile_id': '172f7b0b-16b2-3b81-a92f-b7ac1ad253df'}, {'id': '0da4e6cb-9017-817e-1ec6-1dce37fba867', 'currency': 'BCH', 'balance': '0.0000000000000000', 'available': '0', 'hold': '0.0000000000000000', 'profile_id': '172f7b0b-16b2-3b81-a92f-b7ac1ad253df'}]
type(accts)
returns <class 'requests.models.Response'>
I tried:
caccts = accts.content
BTCaccts = list(filter(lambda cur: cur['currency'] == 'BTC', caccts))
However, I am getting: TypeError: 'int' object is not subscriptable.
I have also tried caccts = accts.text but that doesn't work either.
Thanks

Categories