Better way of grabbing elements from JSON object? - python

This program takes input from a web socket in the form of a JSON object that represents the order book of multiple bitcoin exchanges combined. I have modified the example by deleting the other bids and asks from the first section. The first bid and first ask are all I need to grab.
{
"payload": {
"asks": [
[
8329.01,
0.19875089,
"gemini"
],
],
"bids": [
[
8330.55,
16.04230494,
"market1"
],
],
"currency": "usd",
"lastpublished": 1579970355700,
"lastupdated": 1579970355660,
"market_making": {
"asks": [
[
8344.88,
0.57580068,
"bittrex"
],
[
8336.48,
2,
"bitstamp"
],
[
8330.56,
0.18606522,
"market1"
],
[
8329.01,
0.19875089,
"gemini"
]
],
"bids": [
[
8325.271,
0.0766122,
"bittrex"
],
[
8325.51,
1.1984,
"bitstamp"
],
[
8329,
13.07297146,
"gemini"
],
[
8330.55,
16.04230494,
"market1"
]
]
},
"pair": "btcusd",
"timestamps": {
"bitstamp": [
1579970355573,
1579970355573
],
"bittrex": [
1579970354809,
1579970355010
],
"gemini": [
1579970355374,
1579970355376
],
"market1": [
1579970354799,
1579970354799
]
}
},
"recipient": "orderbook.sfox.btcusd",
"sequence": 2,
"timestamp": 1579970355757434509
}
When making my program I couldn't get json.loads() to return a list or dict, instead I could only get a string result. My code right now just finds the slice where both of these elements should be, but that seems inefficient, and causes issues when the message isn't as I expect.
async def main(uri):
async with websockets.connect(uri) as ws:
subscribe_msg = {
"type": "subscribe",
"feeds": ["orderbook.sfox.btcusd"],
}
await ws.send(json.dumps(subscribe_msg))
async for msg in ws:
#print(msg)
json.loads(msg)
if msg[2] == "s":
ask = float(msg[msg.find("asks") + 8 : msg.find(",", msg.find("asks")+8)])
asksize = float(msg[msg.find(",", msg.find("asks")+8)+1:
msg.find(",", msg.find(",", msg.find("asks")+8)+1)])
bid = float(msg[msg.find("bids") + 8 : msg.find(",", msg.find("bids")+8)])
bidsize = float(msg[msg.find(",", msg.find("bids")+8)+1:
msg.find(",", msg.find(",", msg.find("bids")+8)+1)])
time = msg[msg.find("timestamp") + 11 :msg.find(",",msg.find("timestamp") + 11)]
oppmonitor(bid, bidsize, ask, asksize)
print("Time", time, "Bid", bid, "Bid Size", bidsize, "Ask", ask, "Ask Size", asksize)
else:
print("Starting Message")
The program works I just need a more efficient way of getting the bid and ask. Preferably one that doesn't involve slicing the json object.

Related

To find a time zone where all 8 positions in a specific time zone exist

test = {"19:00" : {
"MT": [
"Husky",
"Joke Bear",
"꾸랭"
],
"ST": [
"Husky",
"Joke Bear",
"꾸랭"
],
"MH": [
"히와"
],
"SH": [
"네모",
"러나"
],
"D1": [
"스테잇",
"네모",
"몽구",
"Husky"
],
"D2": [
"스테잇",
"네모",
"몽구",
"Husky"
],
"D3": [
"은빈"
],
"D4": [
"네모",
"은빈",
"Husky"
]
}}
position_list ={ #expect result
"MT": '꾸랭',
"ST": 'Joke Bear',
"MH": '히와',
"SH": '러나',
"D1": '스테잇',
"D2": '몽구',
"D3": '은빈',
"D4": '네모'
}
In the time between 18:00 and 05:00,
We're conducting a survey of party members' schedules for 8 positions
Some party members can play different positions
In conclusion, I'd like to have a non-redundant number of people
I'd like to do a headcount on 8 positions
I've tried many different ways, but it's too difficult, so I'm looking for help

Returning parent json key after filtering for a specific key:value pair

I am call some API that returns a large API block. I need some help figuring out the most efficient way of filtering json. I've only ever interacted with specific sets or fields but not identifying a single key:value pair and then finding the parent. Once I find the parent, i want to only return the parent block. How would I go about doing it? I'm also trying to understand what kind of logic to use here.
Sample Block below. I would want to find 'itemtype:19' and then return '86' and then once I have '86' i can grab the values i need from 86. Example [86][itemDefinition][name].
},
"86":{
"saleStatus":8,
"failureIndexes":[
3
],
"augments":0,
"vendorItemIndex":86,
"itemHash":1476367343,
"quantity":1,
"costs":[
{
"itemHash":4046539562,
"quantity":10
}
],
"itemDefinition":{
"displayProperties":{
"description":"",
"name":"Sword Ammo Finder",
"icon":"/common/destiny2_content/icons/793bc0219a88f4454e413217628c40f0.png",
"iconSequences":[
{
"frames":[
"/common/destiny2_content/icons/793bc0219a88f4454e413217628c40f0.png"
]
},
{
"frames":[
"/common/destiny2_content/icons/e0d0166080ae8c0630338738ac6cff04.png"
]
}
],
"hasIcon":True
},
"tooltipNotifications":[
],
"collectibleHash":1263137395,
"backgroundColor":{
"colorHash":0,
"red":0,
"green":0,
"blue":0,
"alpha":0
},
"itemTypeDisplayName":"Helmet Armor Mod",
"uiItemDisplayStyle":"ui_display_style_energy_mod",
"itemTypeAndTierDisplayName":"Common Helmet Armor Mod",
"displaySource":"",
"tooltipStyle":"build",
"action":{
"verbName":"Dismantle",
"verbDescription":"",
"isPositive":False,
"requiredCooldownSeconds":0,
"requiredItems":[
],
"progressionRewards":[
],
"actionTypeLabel":"shard",
"rewardSheetHash":0,
"rewardItemHash":0,
"rewardSiteHash":0,
"requiredCooldownHash":0,
"deleteOnAction":True,
"consumeEntireStack":False,
"useOnAcquire":False
},
"inventory":{
"maxStackSize":1,
"bucketTypeHash":2422292810,
"recoveryBucketTypeHash":0,
"tierTypeHash":3340296461,
"isInstanceItem":False,
"nonTransferrableOriginal":False,
"tierTypeName":"Common",
"tierType":2,
"expirationTooltip":"",
"expiredInActivityMessage":"",
"expiredInOrbitMessage":"",
"suppressExpirationWhenObjectivesComplete":True
},
"plug":{
"insertionRules":[
],
"plugCategoryIdentifier":"enhancements.v2_head",
"plugCategoryHash":2912171003,
"onActionRecreateSelf":False,
"actionRewardSiteHash":0,
"actionRewardItemOverrideHash":0,
"insertionMaterialRequirementHash":1564811296,
"previewItemOverrideHash":0,
"enabledMaterialRequirementHash":0,
"enabledRules":[
],
"uiPlugLabel":"",
"plugStyle":0,
"plugAvailability":0,
"alternateUiPlugLabel":"",
"alternatePlugStyle":0,
"isDummyPlug":False,
"energyCost":{
"energyCost":2,
"energyTypeHash":728351493,
"energyType":1
}
},
"acquireRewardSiteHash":0,
"acquireUnlockHash":0,
"investmentStats":[
{
"statTypeHash":3779394102,
"value":2,
"isConditionallyActive":False
}
],
"perks":[
{
"requirementDisplayString":"",
"perkHash":3553498179,
"perkVisibility":0
}
],
"allowActions":True,
"doesPostmasterPullHaveSideEffects":False,
"nonTransferrable":True,
"itemCategoryHashes":[
59,
4104513227,
1362265421
],
"specialItemType":0,
"itemType":19,
"itemSubType":0,
"classType":3,
"breakerType":0,
"equippable":False,
"defaultDamageType":0,
"isWrapper":False,
"hash":1476367343,
"index":8169,
"redacted":False,
"blacklisted":False
}
},
"170":{
"saleStatus":1,
"failureIndexes":[
],
"augments":0,
"vendorItemIndex":170,
"itemHash":2979281381,
"quantity":1,
"costs":[
{
"itemHash":3853748946,
"quantity":1
},
{
"itemHash":1022552290,
"quantity":10
},
{
"itemHash":2014411539,
"quantity":25
},
{
"itemHash":3159615086,
"quantity":5000
}
],
"overrideNextRefreshDate":"2020-09-28T17:00:00Z",
"itemDefinition":{
"displayProperties":{
"description":"A collection of universal components that can be used to infuse power between gear items. Can be purchased from the Gunsmith or acquired from special reward sources.",
"name":"Upgrade Module",
"icon":"/common/destiny2_content/icons/62b016b25d8589f2b15c38890d2b24c3.jpg",
"hasIcon":True
},
"tooltipNotifications":[
],
"backgroundColor":{
"colorHash":0,
"red":94,
"green":12,
"blue":142,
"alpha":255
},
"itemTypeDisplayName":"Material",
"uiItemDisplayStyle":"",
"itemTypeAndTierDisplayName":"Legendary Material",
"displaySource":"",
"action":{
"verbName":"Discard",
"verbDescription":"",
"isPositive":False,
"requiredCooldownSeconds":0,
"requiredItems":[
],
"progressionRewards":[
],
"rewardSheetHash":0,
"rewardItemHash":0,
"rewardSiteHash":0,
"requiredCooldownHash":0,
"deleteOnAction":True,
"consumeEntireStack":False,
"useOnAcquire":False
},
"inventory":{
"stackUniqueLabel":"v460.materials.currencies.infusion_token",
"maxStackSize":25,
"bucketTypeHash":1469714392,
"recoveryBucketTypeHash":215593132,
"tierTypeHash":4008398120,
"isInstanceItem":False,
"nonTransferrableOriginal":False,
"tierTypeName":"Legendary",
"tierType":5,
"expirationTooltip":"",
"expiredInActivityMessage":"",
"expiredInOrbitMessage":"",
"suppressExpirationWhenObjectivesComplete":True
},
"acquireRewardSiteHash":0,
"acquireUnlockHash":0,
"investmentStats":[
],
"perks":[
],
"allowActions":True,
"doesPostmasterPullHaveSideEffects":False,
"nonTransferrable":True,
"itemCategoryHashes":[
40,
52
],
"specialItemType":0,
"itemType":0,
"itemSubType":0,
"classType":3,
"breakerType":0,
"equippable":False,
"defaultDamageType":0,
"isWrapper":False,
"hash":2979281381,
"index":10741,
"redacted":False,
"blacklisted":False
}
},

How to trim JSON array to get specific value

So I am using the Echo Arena API Which gives me some of the following in JSON Format. I am trying to get all of the NAMES of users in the match at the time, as seen here there is player name: rnedds and further down DarkCobra866. How can I get just the names and none of the other information? Using Python 3.
{
"teams":[
{
"players":[
{
"name":"rnedds",
"rhand":[
-3.3230002,
-1.2370001,
-18.701
],
"playerid":0,
"position":[
-2.7520001,
-0.96800005,
-18.622002
],
"lhand":[
-2.414,
-1.5630001,
-18.487001
],
"userid":1663152230440088,
"stats":{ }
},
{
"name":"DarkCobra866",
"rhand":[
-5.3710003,
-1.978,
-7.5110002
],
"playerid":4,
"position":[
-5.5280004,
-1.3520001,
-7.4040003
],
"lhand":[
-5.6520004,
-1.7540001,
-7.4020004
],
"userid":2649496045086049,
"stats":{ }
}
]
}
]
}
Currently, my code looks like this for other information in the API
matchdetails = {
'echosessionid' : data['sessionid'],
'echoclientname' : data['client_name'],
'echogameclockdisplay' : data['game_clock_display'],
'echogamestatus' : data['game_status']
}
currentMatchDetails = json.dumps(matchdetails)
Load your JSON string into a dictionary like this:
import json
json_text = '''
{
"teams":[
{
"players":[
{
"name":"rnedds",
"rhand":[
-3.3230002,
-1.2370001,
-18.701
],
"playerid":0,
"position":[
-2.7520001,
-0.96800005,
-18.622002
],
"lhand":[
-2.414,
-1.5630001,
-18.487001
],
"userid":1663152230440088,
"stats":{ }
},
{
"name":"DarkCobra866",
"rhand":[
-5.3710003,
-1.978,
-7.5110002
],
"playerid":4,
"position":[
-5.5280004,
-1.3520001,
-7.4040003
],
"lhand":[
-5.6520004,
-1.7540001,
-7.4020004
],
"userid":2649496045086049,
"stats":{ }
}
]
}
]
}
'''
data = json.loads(json_text)
players = [player['name'] for team in data['teams'] for player in team['players']]
print(players)
The above code will result in:
['rnedds', 'DarkCobra866']

Django get value from JSON data

I am trying to play with an open fda API. So far everything works well. Issue is coming for nested JSON data.
Here is my Json data:
{
"seriousnessother": "1",
"reportduplicate": {
"duplicatenumb": "US-BRISTOL-MYERS SQUIBB COMPANY-BMS-2017-086135",
"duplicatesource": "BRISTOL MYERS SQUIBB"
},
"safetyreportversion": "1",
"receiptdate": "20170927",
"duplicate": "1",
"seriousnessdeath": "1",
"receivedate": "20170927",
"patient": {
"reaction": [
{
"reactionmeddrapt": "Death",
"reactionmeddraversionpt": "20.1",
"reactionoutcome": "5"
},
{
"reactionmeddrapt": "Product use in unapproved indication",
"reactionmeddraversionpt": "20.1",
"reactionoutcome": "6"
}
],
"patientsex": "1",
"drug": [
{
"drugstartdateformat": "102",
"medicinalproduct": "OPDIVO",
"drugindication": "COLORECTAL CANCER",
"drugcharacterization": "1",
"drugadministrationroute": "065",
"drugenddateformat": "102",
"drugseparatedosagenumb": "1",
"drugstructuredosageunit": "032",
"openfda": {
"manufacturer_name": [
"E.R. Squibb & Sons, L.L.C."
],
"unii": [
"31YO63LBSN"
],
"product_type": [
"HUMAN PRESCRIPTION DRUG"
],
"spl_set_id": [
"f570b9c4-6846-4de2-abfa-4d0a4ae4e394"
],
"route": [
"INTRAVENOUS"
],
"generic_name": [
"NIVOLUMAB"
],
"brand_name": [
"OPDIVO"
],
"product_ndc": [
"0003-3772",
"0003-3734",
"0003-3774"
],
"pharm_class_epc": [
"Programmed Death Receptor-1 Blocking Antibody [EPC]"
],
"substance_name": [
"NIVOLUMAB"
],
"spl_id": [
"2d33126d-5115-459e-bcaf-d0ace4fbe94e"
],
"pharm_class_moa": [
"Programmed Death Receptor-1-directed Antibody Interactions [MoA]"
],
"application_number": [
"BLA125554"
],
"nui": [
"N0000191259",
"N0000191260"
],
"package_ndc": [
"0003-3734-13",
"0003-3772-11",
"0003-3774-12"
]
},
"drugstructuredosagenumb": "1",
"drugintervaldosageunitnumb": "2",
"drugstartdate": "20160907",
"actiondrug": "5",
"activesubstance": {
"activesubstancename": "NIVOLUMAB"
},
"drugintervaldosagedefinition": "803",
"drugauthorizationnumb": "125554",
"drugrecurreadministration": "3",
"drugdosagetext": "1 DF, Q2WK",
"drugenddate": "20161222",
"drugadditional": "3"
}
]
},
"occurcountry": "US",
"reporttype": "1",
"companynumb": "US-BRISTOL-MYERS SQUIBB COMPANY-BMS-2017-086135",
"safetyreportid": "14015990",
"sender": {
"senderorganization": "FDA-Public Use",
"sendertype": "2"
},
"transmissiondate": "20171128",
"fulfillexpeditecriteria": "1",
"transmissiondateformat": "102",
"receiptdateformat": "102",
"receiver": {
"receiverorganization": "FDA",
"receivertype": "6"
},
"serious": "1",
"receivedateformat": "102",
"primarysource": {
"reportercountry": "US",
"qualification": "5"
},
"primarysourcecountry": "US"
}
Here is my view to call this data and convert to Django data.
json_data = open('/users/downloads/drug-bad.json').read()
response = json.loads(json_data)
a=0
b=0
for data in response['results']:
#try:
seriousnessother = data.get('seriousnessother')
reportduplicate_duplicatenumb = data['reportduplicate'].get('duplicatenumb')
reportduplicate_duplicatesource = data['reportduplicate'].get('duplicatesource')
safetyreportversion = data.get('safetyreportversion')
receiptdate = data.get('receiptdate')
duplicate = data.get('duplicate')
seriousnessdeath = data.get('seriousnessdeath')
receivedate = data.get('receivedate')
patient_reaction_reactionmeddrapt = data['patient']['reaction'].get('reactionmeddrapt')
patient_reaction_reactionmeddraversionpt = data['patient']['reaction'].get('reactionmeddraversionpt')
patient_reaction_reactionoutcome = data['patient']['reaction'].get('reactionoutcome')
patient_patientsex = data['patient'].get('patientsex')
patient_drug_medicinalproduct = data['patient']['drug'].get('medicinalproduct')
patient_drug_drugindication = data['patient']['drug'].get('drugindication')
patient_drug_drugcharacterization = data['patient']['drug'].get('drugcharacterization')
patient_drug_drugadministrationroute = data['patient']['drug'].get('drugadministrationroute')
patient_drug_drugseparatedosagenumb = data['patient']['drug'].get('drugseparatedosagenumb')
patient_drug_drugstructuredosageunit = data['patient']['drug'].get('drugstructuredosageunit')
patient_drug_openfda_manufacturer_name = data['patient']['drug']['openfda']['manufacturer'].get('name')
patient_drug_openfda_unii = data['patient']['drug']['openfda'].get('unii')
patient_drug_openfda_product_type = data['patient']['drug']['openfda']['product'].get('type')
patient_drug_openfda_spl_set_id = data['patient']['drug']['openfda']['spl']['set'].get('id')
patient_drug_openfda_route = data['patient']['drug']['openfda'].get('route')
patient_drug_openfda_generic_name = data['patient']['drug']['openfda']['generic'].get('name')
patient_drug_openfda_brand_name = data['patient']['drug']['openfda']['brand'].get('name')
patient_drug_openfda_product_ndc = data['patient']['drug']['openfda']['product'].get('ndc')
patient_drug_openfda_pharm_class_epc = data['patient']['drug']['openfda']['pharm']['class'].get('epc')
patient_drug_openfda_substance_name = data['patient']['drug']['openfda']['substance'].get('name')
patient_drug_openfda_spl_id = data['patient']['drug']['openfda']['spl'].get('id')
patient_drug_openfda_pharm_class_moa = data['patient']['drug']['openfda']['pharm']['class'].get('moa')
patient_drug_openfda_application_number = data['patient']['drug']['openfda']['application'].get('number')
patient_drug_openfda_nui = data['patient']['drug']['openfda'].get('nui')
patient_drug_openfda_package_ndc = data['patient']['drug']['openfda']['package'].get('ndc')
patient_drug_drugstructuredosagenumb = data['patient']['drug'].get('drugstructuredosagenumb')
patient_drug_drugintervaldosageunitnumb = data['patient']['drug'].get('drugintervaldosageunitnumb')
patient_drug_drugstartdate = data['patient']['drug'].get('drugstartdate')
patient_drug_actiondrug = data['patient']['drug'].get('actiondrug')
patient_drug_activesubstance_activesubstancename = data['patient']['drug']['activesubstance'].get('activesubstancename')
patient_drug_drugintervaldosagedefinition = data['patient']['drug'].get('drugintervaldosagedefinition')
patient_drug_drugauthorizationnumb = data['patient']['drug'].get('drugauthorizationnumb')
patient_drug_drugrecurreadministration = data['patient']['drug'].get('drugrecurreadministration')
patient_drug_drugdosagetext = data['patient']['drug'].get('drugdosagetext')
patient_drug_drugenddate = data['patient']['drug'].get('drugenddate')
patient_drug_drugadditional = data['patient']['drug'].get('drugadditional')
occurcountry = data.get('occurcountry')
reporttype = data.get('reporttype')
companynumb = data.get('companynumb')
safetyreportid = data.get('safetyreportid')
sender_senderorganization = data['sender'].get('senderorganization')
sender_sendertype = data['sender'].get('sendertype')
fulfillexpeditecriteria = data.get('fulfillexpeditecriteria')
receiver_receiverorganization = data['receiver'].get('receiverorganization')
receiver_receivertype = data['receiver'].get('receivertype')
serious = data.get('serious')
primarysource_reportercountry = data['primarysource'].get('reportercountry')
primarysource_qualification = data['primarysource'].get('qualification')
primarysourcecountry = data.get('primarysourcecountry')
I am getting following error:
patient_reaction_reactionmeddrapt = data['patient']['reaction'].get('reactionmeddrapt')
AttributeError: 'list' object has no attribute 'get'
Note that there are many data in response result. It could be that one of result does not have patient field. But as get method should return None if it does not exist.
I want either the field value or None.
It works for simple Json data but error comes when there are array/list inside array/list.
Since reaction is list you should do something like this:
reactions = data['patient']['reaction']
if reactions and isinstance(reactions, list):
for reaction in reactions:
patient_reaction_reactionmeddrapt = reaction.get('reactionmeddrapt')
else:
patient_reaction_reactionmeddrapt = data['patient']['reaction'].get('reactionmeddrapt')
instead of simple:
patient_reaction_reactionmeddrapt = data['patient']['reaction'].get('reactionmeddrapt')
data['patient']['reaction'] in your code return list objects. So you need to iterate over it to get reactionmeddrapt for each list element.
Given your input json:
"patient": {
"reaction": [
{
"reactionmeddrapt": "Death",
"reactionmeddraversionpt": "20.1",
"reactionoutcome": "5"
},
{
"reactionmeddrapt": "Product use in unapproved indication",
"reactionmeddraversionpt": "20.1",
"reactionoutcome": "6"
}
],
The data value for "reactions" is a list. Also as I understand it, you want to get the "reactionmeddrapt" attribute value or None if you don't have a data value for "patient".
You could do something like this:
try:
reactions = data['patient']['reaction']
except KeyError:
return None
if reactions and isinstance(reactions, list):
# Assuming you want to iterate over the list
for reaction in reactions:
reactionmeddrapt = reaction.get('reactionmeddrapt')

Parsing json with python3

Newbie python programmer here, I have the following json response:
[
{
"type": "Incursion",
"state": "mobilizing",
"influence": 1,
"has_boss": true,
"faction_id": 500019,
"constellation_id": 20000739,
"staging_solar_system_id": 30005054,
"infested_solar_systems": [
30005050,
30005051,
30005052,
30005053,
30005054,
30005055
]
},
{
"type": "Incursion",
"state": "established",
"influence": 0,
"has_boss": false,
"faction_id": 500019,
"constellation_id": 20000035,
"staging_solar_system_id": 30000248,
"infested_solar_systems": [
30000244,
30000245,
30000246,
30000247,
30000248,
30000249,
30000250,
30000251,
30000252,
30000253
]
},
{
"type": "Incursion",
"state": "mobilizing",
"influence": 0,
"has_boss": false,
"faction_id": 500019,
"constellation_id": 20000161,
"staging_solar_system_id": 30001101,
"infested_solar_systems": [
30001097,
30001098,
30001099,
30001100,
30001101,
30001102
]
},
{
"type": "Incursion",
"state": "established",
"influence": 0,
"has_boss": false,
"faction_id": 500019,
"constellation_id": 20000647,
"staging_solar_system_id": 30004434,
"infested_solar_systems": [
30004425,
30004426,
30004427,
30004428,
30004429,
30004430,
30004431,
30004432,
30004433,
30004434,
30004435
]
},
{
"type": "Incursion",
"state": "established",
"influence": 0.061500001698732376,
"has_boss": false,
"faction_id": 500019,
"constellation_id": 20000570,
"staging_solar_system_id": 30003910,
"infested_solar_systems": [
30003904,
30003906,
30003908,
30003909,
30003910,
30003903
]
}
]
The original code was written to parse an XML reponse.
This is the code in question:
incursion_constellations = []
if (online):
inc = urllib2.urlopen('https://esi.tech.ccp.is/latest/incursions/')
else:
inc = file(r'incursions.json', 'r')
jinc = json.load(inc)
for j in jinc['items']:
incursion_constellations.append(str(j['constellation']['id_str']))
for s in all_stations:
cur.execute("SELECT constellationID FROM mapSolarSystems WHERE solarSystemID = " + str(s['ssid']))
res = cur.fetchone()
cid = str(res[0])
s['incursion'] = cid in incursion_constellations
The area I have having a hard time understanding is this: for j in jinc['items']:
I am getting this error:
Traceback (most recent call last):
File "./stations.py", line 201, in <module>
for j in jinc['items']:
TypeError: list indices must be integers, not str
Can anyone help me understand how to convert this into being able to parse the json response and retrieve the constellation_id and append it to a list?
Thanks in advance.
Change your original loop to:
for j in jinc:
incursion_constellations.append(str(j['constellation_id']))
But you need to be sure that constellation_id in json is the same id that was under ['constellation']['id_str'] previously
Seeing the [ and ] at the beginning and the end of the response, it seems like this json response is list, not a dict, just as your error is suggesting.
If it is a list, you should be using integer as index, instead of str, like you'd do in dict. Hence, your code should be something like
jinc[0]['constellation_id']
(I don't see where the ['constellation']['id_str'] part comes from)
whatever goes inside the [ and ] is in a list, and should be using an integer index. the ones in { and } are in dict, and should use str index.
to loop through it, just use range and len.
a similar question has been answered here.

Categories

Resources