So I'm fairly new to Python and development in general. So what I'm trying to do is print all the values in an object if the name/value pair "oranges: "555555" exists. I've listed my request results below and the code that I currently have running.
query_response = requests.get(GET_URL, headers=GIT_HEADERS)
jsonResults = query_response.json()
This returns results like so
[
{
"oranges": "555555",
"from": "California"
"actor": "Tom Brady",
"action": "wins_all_superbowls"
"repo": "Love_Snow_Mountains",
"repo_id": 66666,
"org_id": 85555
"@timestamp": 1666646455465,
"business_id": 454545,
"actor_location": {
"location": {
"lat": 0.0,
"lon": 0.0
}
}
]
Here's the code that I currently have:
if (obj['oranges'] == '555555' for obj in jsonResults):
print(vars(object)) //this is the part that I'm stuck at
So if "oranges" : "555555" exists in an array, I want to print all the other values and then throw them into a row in a csv file. I think I can figure out the row and csv stuff but I just want to be able to print all those other values if "oranges" : "555555" does exists.
CodePudding user response:
Iterate with a for, and filter with an if
for_csv = []
for obj in jsonResults:
if obj['oranges'] == '555555':
for_csv.append(obj)
for k, v in obj.items():
print(f"{k}={v}")
For the CSV output, you'll need to handle multilevel dict at actor_location
CodePudding user response:
It's better you use get method, so you don't get an error if the dictionary key you are requesting doesn't exist.
if any(obj.get("oranges") == '555555' for obj in jsonResults):
CodePudding user response:
You're very close; you want to use the any function:
if any(obj['oranges'] == '555555' for obj in jsonResults):
print(jsonResults)
The expression obj['oranges'] == '555555' for obj in jsonResults is a generator that produces a True or False value for each obj in jsonResults. The any function will go through that generator and tell you whether any of those values are True.
