I'm trying to go through a JSON by using python but I can't access the "mbid" node. I want to print only the first "mbid" node.
Here is my function :
def get_data():
newJsonx = dict()
for item in data["resultsPage"]["results"]["calendarEntry"]:
mbid = item["event"]["performance"][0]["artist"]["identifier"][0]["mbid"]
With this function i get this error : IndexError: list index out of range
but when I'm doing
def get_data():
newJsonx = dict()
for item in data["resultsPage"]["results"]["calendarEntry"]:
mbid = item["event"]["performance"][0]["artist"]["identifier"]
And print(mbid), I'm getting a correct answer :
"identifier": [
{
"mbid": "6655955b-1c1e-4bcb-84e4-81bcd9efab30"
},
{
"mbid": "1b1b1b1b-1c1d"
}
]
So means I don't have a problem with the data. Maybe I'm doing something wrong with the second array?
Here is an example of the JSON structure :
{
"resultsPage": {
"status": "ok",
"results": {
"calendarEntry": [
{
"reason": {
},
"event": {
"performance": [
{
"id": 72641494,
"displayName": "Arnalds",
"artist": {
"id": 590465,
"identifier": [
{
"mbid": "6655955b-1c1e-4bcb-84e4-81bcd9efab30"
},
{
"mbid": "1b1b1b1b-1c1d"
}
]
}
}
]
}
}
]
}
}
}
Thanks for your time
def get_data():
newJsonx = dict()
for item in data["resultsPage"]["results"]["calendarEntry"]:
performance=item["event"]["performance"]
if performace:
identifier=performace[0]["artist"]["identifier"]
if identifier:
mbid=identifier[0]["mbid"]
Related
I have the following json output assigned to a variable called "mydict":
{
"data": {
"endpoints": {
"edges": [
{
"node": {
"name": "test1.net",
"ipAddress": "1.2.3.4"
}
},
{
"node": {
"name": "test2.net",
"ipAddress": "4.3.2.1"
}
},
{
"node": {
"name": "test3.net",
"ipAddress": "0.0.0.0"
}
}
]
}
}
}
I'm able to print out a single "name" value with:
print("Dictionary contains: ",mydict['data']['endpoints']['edges'][1]['node']['name'])
But with how the data is nested, I'm not sure how to iterate through each "name" to get a print of only those values. Any recommendations? Thank you!
for edge in mydict['data']['endpoints']['edges']:
print(edge['node']['name'])
I am writing a parser that goes through a list of data that is roughly formatted:
{
"teachers": [
{
"fullName": "Testing",
"class": [
{
"className": "Counselor",
"school": {
"id": "2b6671cb-617d-48d6-b0b5-3d44ce4da21c"
}
}
]
},
...
}
The parser is supposed to check for duplicate names within this json object, and when it stumbles upon said duplicate name, append the class to the class array.
So for example:
{
"teachers": [
{
"fullName": "Testing",
"class": [
{
"className": "Counselor",
"school": {
"id": "2b6671cb-617d-48d6-b0b5-3d44ce4da21c"
}
}
]
},
{
"fullName": "Testing",
"class": [
{
"className": "Math 8",
"school": {
"id": "2b6671cb-617d-48d6-b0b5-3d44ce4da21c"
}
}
]
},
...
}
Would return
{
"teachers": [
{
"fullName": "Testing",
"class": [
{
"className": "Counselor",
"school": {
"id": "2b6671cb-617d-48d6-b0b5-3d44ce4da21c"
}
},
{
"className": "Math 8",
"school": {
"id": "2b6671cb-617d-48d6-b0b5-3d44ce4da21c"
}
},
]
},
...
}
My current parser works just fine for most objects, however for some reason it doesn't catch some of the duplicates despite the names being the exact same, and also is appending the string
}7d-48d6-b0b5-3d44ce4da21c"
}
}
]
}
]
to the end of the json document. I am not sure why it would do this considering I am just dumping the modified json (which only is modified within the array).
My parser code is:
i_duplicates = []
name_duplicates = []
def converter():
global i_duplicates
file = open("final2.json", "r+")
infinite = json.load(file)
for i, teacher in enumerate(infinite["teachers"]):
class_name = teacher["class"][0]["className"]
class_data = {
"className": class_name,
"school": {
"id": "2b6671cb-617d-48d6-b0b5-3d44ce4da21c"
}
}
d = {
"fullName": teacher["fullName"],
"index": i
}
c = {
"fullName": teacher["fullName"]
}
if c in name_duplicates:
infinite["teachers"][search(i_duplicates, c["fullName"])]["class"].append(class_data)
infinite["teachers"].pop(i)
file.seek(0)
json.dump(infinite, file, indent=4)
else:
i_duplicates.append(d)
name_duplicates.append(c)
def search(a, t):
for i in a:
if i["fullName"] == t:
return i["index"]
print(Fore.RED + "not found" + Fore.RESET)
I know I am going about this inefficiently, but I am not sure how to fix the issues the current algorithm is having. Any feedback appreciated.
I'm currently working with some JSON data that is presenting a challenge, i need to print the device name in my script next to the latency float, i can easily print the latency float as there is a key:value , however the device name does not sit the same, therefore i cannot figure out how to print this especially as it changes for each API Url i am looping through to retrieve the data
The data i want to print is "DEVICE123-Et10"
See JSON data below,
{
"notifications": [
{
"timestamp": "511513234234",
"path_elements": [
"Devices",
"DEVICE1",
"versioned-data",
"connectivityMonitor",
"status",
"hostStatus",
"DEVICE123-Et10",
"defaultStats"
],
"updates": {
"httpResponseTime": {
"key": "httpResponseTime",
"value": {
"float": 0
}
}
}
},
{
"timestamp": "15153324243",
"path_elements": [
"Devices",
"DEVICE1",
"versioned-data",
"connectivityMonitor",
"status",
"hostStatus",
"DEVICE123-Et10",
"defaultStats"
],
"updates": {
"packetLoss": {
"key": "packetLoss",
"value": {
"int": 0
}
}
}
},
{
"timestamp": "151522324234",
"path_elements": [
"Devices",
"DEVICE1",
"versioned-data",
"connectivityMonitor",
"status",
"hostStatus",
"DEVICE123-Et10",
"defaultStats"
],
"updates": {
"latency": {
"key": "latency",
"value": {
"float": 0.238756565643454
}
}
}
},
{
"timestamp": "158056745645645",
"path_elements": [
"Devices",
"DEVICE1",
"versioned-data",
"connectivityMonitor",
"status",
"hostStatus",
"DEVICE123-Et10",
"defaultStats"
],
"updates": {
"jitter": {
"key": "jitter",
"value": {
"float": 0.03500000213213
}
}
}
}
]
}
Current code i am using to loop through my URL list and get the latency:
jsonrequest = requests.get(url, cookies=cookies, verify=False).json()
try:
print(jsonrequest['notifications'][2]['updates']['latency']['value']['float'])
except KeyError:
print(jsonrequest['notifications'][1]['updates']['latency']['value']['float'])```
I went ahead and wrote a script to do what you wanted. It loops through all the notifications until a "latency" update is found. Then it takes the second-to-last item from the list, since it's always second to last.
import json
import requests
data = requests.get(url, cookies=cookies, verify=False).json()
notifications = data["notifications"]
for notification in notifications:
if notification["updates"].get("latency"):
latency = notification["updates"]["latency"]["value"]["float"]
name = notification["path_elements"][-2]
print(name, latency)
When ever i am calling my service from alexa i am getting None not the values of slot which i should get.
i have intent schema like :
{
"interactionModel": {
"languageModel": {
"invocationName": "name_of_app",
"intents": [
{
"name": "AMAZON.CancelIntent",
"samples": []
},
{
"name": "AMAZON.HelpIntent",
"samples": []
},
{
"name": "AMAZON.StopIntent",
"samples": []
},
{
"name": "EventsIntent",
"slots": [
{
"name": "City",
"type": "AMAZON.GB_CITY"
}
],
"samples": [
"whats {City}",
"whats going on in {City} ",
"tell me about {City}"
]
}
],
"types": []
}
}
}
my Flask-Ask code where i want to import the city but when ever i run my code i get None on the place of a city name.
#ask.intent('EventsIntent', mapping={'city': 'City'})
def weather(city):
return statement('you have selected {}'.format(city))
You need to use convert rather than mapping it should work nicely please try
#ask.intent('EventsIntent', convert={'City': str})
def weather(City):
return statement('you have selected {}'.format(City))
this is a sample of my json file:
{
"pops": [{
"name": "pop_a",
"subnets": {
"Public": ["1.1.1.0/24,2.2.2.0/24"],
"Private": ["192.168.0.0/24,192.168.1.0/24"],
"more DATA":""
}
},
{
"name": "pop_b",
"subnets": {
"Public": ["3.3.3.0/24,4.4.4.0/24"],
"Private": ["192.168.2.0/24,192.168.3.0/24"],
"more DATA":""
}
}
]
}
after i read it, i want to make a dic object and store some of the things that i need from this file.
i want my object to be like this ..
[{
"name": "pop_a",
"subnets": {"Public": ["1.1.1.0/24,2.2.2.0/24"],"Private": ["192.168.0.0/24,192.168.1.0/24"]}
},
{
"name": "pop_b",
"subnets": {"Public": ["3.3.3.0/24,4.4.4.0/24"],"Private": ["192.168.2.0/24,192.168.3.0/24"]}
}]
then i want to be able to access some of the public/private values
here is what i tried, and i know there is update(), setdefault() that gave also same unwanted results
def my_funckion():
nt_json = [{'name':"",'subnets':[]}]
Pname = []
Psubnet= []
for pop in pop_json['pops']: # it print only the last key/value
nt_json[0]['name']= pop['name']
nt_json[0]['subnet'] = pop['subnet']
pprint (nt_json)
for pop in pop_json['pops']:
"""
it print the names in a row then all of the ipss
"""
Pname.append(pop['name'])
Pgre.append(pop['subnet'])
nt_json['pop_name'] = Pname
nt_json['subnet']= Psubnet
pprint (nt_json)
Here's a quick solution using list comprehension. Note that this approach can be taken only with enough knowledge of the json structure.
>>> import json
>>>
>>> data = ... # your data
>>> new_data = [{ "name" : x["name"], "subnets" : {"Public" : x["subnets"]["Public"], "Private" : x["subnets"]["Private"]}} for x in data["pops"]]
>>>
>>> print(json.dumps(new_data, indent=2))
[
{
"name": "pop_a",
"subnets": {
"Private": [
"192.168.0.0/24,192.168.1.0/24"
],
"Public": [
"1.1.1.0/24,2.2.2.0/24"
]
}
},
{
"name": "pop_b",
"subnets": {
"Private": [
"192.168.2.0/24,192.168.3.0/24"
],
"Public": [
"3.3.3.0/24,4.4.4.0/24"
]
}
}
]