I'm trying to parse through a JSON file and return results only if specific key exists. Here is the example of the JSON:
"phone_numbers": [
{
"id": "123456",
"number": " 11234567890",
"source": "external",
"status": "available",
"number_type": "toll",
"capability": [
"incoming",
"outgoing"
],
"location": "United States",
"assignee": {
"id": "1234",
"name": "John Smith",
"extension_number": 7890,
"type": "user"
},
"site": {
"id": "123456",
"name": "COPQ"
},
"emergency_address": {
"country": "US",
"address_line1": "Testing",
"address_line2": "Testing",
"city": "Testing",
"state_code": "PA",
"zip": "19428"
},
"emergency_address_status": 1
},
So for above I only want to return record if key 'assignee' is present, if not just bypass it. For now I'm just trying to count how many records have 'assignee' but can't get it to work. Here is what I'm using:
counter = 0
for i in user_data['phone_numbers']:
if i['assignee']:
counter = 1
print(counter)
CodePudding user response:
You can use in
keyword. The in
keyword can also be used to check if a value is present in a sequence.
For example,
colors = ["red", "blue", "green"]
print("red" in colors) # True
The solution of your problem is as below-
records = []
for d in user_data["phone_numbers"]:
if "assignee" in d:
records.append(d)
print(len(records))
CodePudding user response:
trying to count how many records have 'assignee'
You can use a generator expression to get that count
sum(1 for p in data["phone_numbers"] if "assignee" in p)
To get a list of all numbers with assignee keys, then a list-comprehension
assignees = [p in data["phone_numbers"] if "assignee" in p]