How to trim JSON array to get specific value - python

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

Related

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 add key to existing dictionary?

I am using python3 and trying to figure out the easiest way to add another layer to my dictionary. I have a dictionary that looks like this.
{ "block1": ["brian"], "block2": ["angel"], "block3": ["sally"] }
How can I add name into the existing dictionary?
{ "name": { "block1": [ "brian" ], "block2": [ "angel" ], "block3": [ "sally" ] } }
d1 = { "block1": ["brian"], "block2": ["angel"], "block3": ["sally"] }
d1 = {"name":d1}
print (d1)

How to get this json object in python?

so I want to get the first key element from this JSON using python 3.7 without knowing its name.
Here is the JSON:
{
"intent":[
{
"confidence":0.99313362101529,
"value":"sendmessage"
}
],
"wikipedia_search_query":[
{
"suggested":true,
"confidence":0.93804001808167,
"value":"message",
"type":"value"
}
],
"messenger_recipient":[
{
"confidence":0.93138399364195,
"value":"me",
"type":"value"
}
]
}
EDIT:
I want to compare the name of the first key like so:
if(jsonobj[0] == "wikipedia_search_query")
dosomething()
While Python 3.6+ does maintain insertion order on dictionaries, there's no guarantee that your incoming JSON will be in the order you expect. That being said, if you can guarantee the insertion order, here's a working example.
import json
js = """{
"intent":[
{
"confidence":0.99313362101529,
"value":"sendmessage"
}
],
"wikipedia_search_query":[
{
"suggested":true,
"confidence":0.93804001808167,
"value":"message",
"type":"value"
}
],
"messenger_recipient":[
{
"confidence":0.93138399364195,
"value":"me",
"type":"value"
}
]
}"""
json_data = json.loads(js)
first_key = next(iter(json_data))
first_value = json_data[next(iter(json_data))]
print(first_key)
print(first_value)
Output
intent
[{'confidence': 0.99313362101529, 'value': 'sendmessage'}]

Turn text list into json formatted list

I have a text file that is formatted like the following, with each hyphen representing a hierarchy for the list item.
category1 : 0120391123123
- subcategory : 0120391123123
-- subsubcategory : 019301948109
--- subsubsubcategory : 013904123908
---- subsubsubsubcategory : 019341823908
- subcategory2 : 0934810923801
-- subsubcategory2 : 09341829308123
category2: 1309183912309
- subcategory : 10293182094
...
How can I programmatically get a list like this into a json format like the following?
[
{
"category1":"0120391123123"
},
[
{
"subcategory":"0120391123123"
},
[
{
"subsubcategory":"019301948109"
},
[
{
"subsubsubcategory":"013904123908"
},
[
{
"subsubsubsubcategory":"019341823908"
}
]
]
]
],
[
{
"subcategory2":"0934810923801"
},
[
{
"subsubcategory2":"09341829308123"
}
]
],
[
{
"category2":"1309183912309"
},
[
{
"subcategory":"10293182094"
}
]
]
]
use a recursive function to split the content of the file to chunks and use divide and conquer
from pprint import pprint
req=[]
startingindex=-1
with open('temp.txt' ,'r') as f:
content=f.read().split('\n')
def foo(splitcontent):
index=0
reqlist=[]
while(index<len(splitcontent)):
if (splitcontent[index][0]!='-'):
key,value=splitcontent[index].split(':')
reqlist.append({key.strip():value.strip()})
index+=1
templist=[]
while(index<len(splitcontent) and splitcontent[index][0]=='-'):
templist.append(splitcontent[index][1:])
index+=1
intermediatelist=foo(templist)
if(intermediatelist):
reqlist.append(intermediatelist)
return reqlist
pprint(foo(content))
OUTPUT
[{'category1': '0120391123123'},
[{'subcategory': '0120391123123'},
[{'subsubcategory': '019301948109'},
[{'subsubsubcategory': '013904123908'},
[{'subsubsubsubcategory': '019341823908'}]]],
{'subcategory2': '0934810923801'},
[{'subsubcategory2': '09341829308123'}]],
{'category2': '1309183912309'},
[{'subcategory': '10293182094'}]]
You can use recursion with itertools.groupby:
s = """
category1 : 0120391123123
- subcategory : 0120391123123
-- subsubcategory : 019301948109
--- subsubsubcategory : 013904123908
---- subsubsubsubcategory : 019341823908
- subcategory2 : 0934810923801
-- subsubcategory2 : 09341829308123
category2: 1309183912309
- subcategory : 10293182094
"""
import re, itertools
data = list(filter(None, s.split('\n')))
def group_data(d):
if len(d) == 1:
return [dict([re.split('\s*:\s*', d[0])])]
grouped = [[a, list(b)] for a, b in itertools.groupby(d, key=lambda x:not x.startswith('-'))]
_group = [[grouped[i][-1], grouped[i+1][-1]] for i in range(0, len(grouped), 2)]
_c = [[dict([re.split('\s*:\s*', i) for i in a]), group_data([c[1:] for c in b])] for a, b in _group]
return [i for b in _c for i in b]
print(json.dumps(group_data(data), indent=4))
Output:
[
{
"category1": "0120391123123"
},
[
{
" subcategory": "0120391123123"
},
[
{
" subsubcategory": "019301948109"
},
[
{
" subsubsubcategory": "013904123908"
},
[
{
" subsubsubsubcategory": "019341823908"
}
]
]
],
{
" subcategory2": "0934810923801"
},
[
{
" subsubcategory2": "09341829308123"
}
]
],
{
"category2": "1309183912309"
},
[
{
" subcategory": "10293182094"
}
]
]
Note: this answer assumes that your final output should have "category2" be at the same level as "category1", since both do not contain a "-" in the front.

Retrieve IP from json with fabric

Hi I have a json something like below i want to retrieve ip_address & store it in any variable in fabric.And if my ip_address (v4) field is array how can i use different ip set automatically on my [env.host] variable.
{
"droplet":{
"id":16549167,
"name":"test",
"memory":512,
"vcpus":1,
"disk":20,
"locked":false,
"status":"active",
"kernel":null,
"created_at":"2016-06-03T07:01:59Z",
"features":[
"ipv6",
"virtio"
],
"next_backup_window":null,
"snapshot_ids":[
],
"image":{
"id":17154032,
"name":"14.04.4 x64",
"distribution":"Ubuntu",
"slug":"ubuntu-14-04-x64",
"public":true,
"regions":[
"nyc1",
"tor1",
"sfo2",
"blr1"
],
"created_at":"2016-05-04T22:25:47Z",
"min_disk_size":20,
"type":"snapshot",
"size_gigabytes":19.68
},
"size":{
"slug":"512mb",
"memory":512,
"available":true
},
"networks":{
"v4":[
{
"ip_address":"104.236.223.78",
"netmask":"255.255.192.0",
"gateway":"104.236.192.1",
"type":"public"
}
],
"v6":[
{
"ip_address":"260:A880:08:001",
"netmask":64,
"gateway":"2604:800:0010:0000:0000:0000:0001",
"type":"public"
}
]
}

Categories

Resources