Looking for a specific value in JSON file

2024/10/15 3:10:55

I have a json file created by a function.

The file is looks like this :

    {"images": [{"image": "/WATSON/VISUAL-REC/../IMAGES/OBAMA.jpg", "classifiers": [{"classes": [{"score": 0.921, "class": "President of the United States", "type_hierarchy": "/person/President of the United States"}, {"score": 0.921, "class": "person"}, {"score": 0.73, "class": "ivory color"}, {"score": 0.648, "class": "Indian red color"}], "classifier_id": "default", "name": "default"}]}], "custom_classes": 0, "images_processed": 1
}

I wrote a function that is going to check is a the value "person" is present. If the value "person" is present, I will increment with

#LOADING MY JSON FILE  
output_file = open(new_json_file).read()
output_json = json.loads(output_file)
#SETTING PERSON VALUE TO 0 
person = 0 
#CONDITIONS 
if "person" in output_json["images"][0]["classifiers"][0]["classes"][0]["class"] :person=1print (' FUNCTION : jsonanalysis // step There is a person in this image')return person
else :person = 0print (' FUNCTION : jsonanalysis // step There is a NO person in this image')return person

I guess This is not the right way to check if the value "person" is returned in the JSON Key since it does not find the value. What Am I missing here ?

I looked into some threads like those and tried to adapt my function:

Parsing values from a JSON file using Python?

Find a value within nested json dictionary in python

But my issue is the "class" key. There is several values for the key "class" ( like "ivory color") not just "person".

Answer

Since the "person" class is not necessarily the first in the first element of the "classes" array. you should iterate over all of the elements there.

for entry in in output_json['images'][0]['classifiers'][0]['classes']:if ('class' in entry) and (entry['class'] == 'person'):person += 1print (' FUNCTION : jsonanalysis // step There is a person in this image')return person

if you want to check if there is 'person' in a class entry in ANY of the images/classifiers, you will need to iterate over those arrays as well:

for image_entry in output_json['images']:for classifier_entry in image_entry['classifiers']:for class_entry in in classifier_entry["classes"]:if class_entry['class'] == 'person':person += 1print (' FUNCTION : jsonanalysis // step There is a person in this image')return person

Note, that if you want to count the total number of 'person' occurrences, you should not return inside the loop, but only after it is completed.

https://en.xdnf.cn/q/117877.html

Related Q&A

How to put many numpy files in one big numpy file without having memory error?

I follow this question Append multiple numpy files to one big numpy file in python in order to put many numpy files in one big file, the result is: import matplotlib.pyplot as plt import numpy as np i…

scraping : nested url data scraping

I have a website name https://www.grohe.com/in In that page i want to get one type of bathroom faucets https://www.grohe.com/in/25796/bathroom/bathroom-faucets/grandera/ In that page there are multiple…

How to trigger an action once on overscroll in Kivy?

I have a ScrollView thats supposed to have an update feature when you overscroll to the top (like in many apps). Ive found a way to trigger it when the overscroll exceeds a certain threshold, but it tr…

Python - Print Each Sentence On New Line

Per the subject, Im trying to print each sentence in a string on a new line. With the current code and output shown below, whats the syntax to return "Correct Output" shown below?Codesentenc…

pyinstaller struct.error: unpack requires a bytes object of length 16 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

Getting the quarter where recession start and recession ends along with the quarter of minimum gdp

Quarter: GDP: GDP change: change 1999q3 9 -- ------ 1999q4 10 1 increase 2000q1 9 -1 decline 2000q2 8 -1 de…

Inherit view and adding fields

I want to add my 2 fields boatlenght and fuelcapacity under price list in product form view but they are not showing up. What did i miss.<?xml version="1.0" encoding="utf-8"?&g…

Linux and python: Combining multiple wave files to one wave file

I am looking for a way that I can combine multiple wave files into one wave file using python and run it on linux. I dont want to use any add on other than the default shell command line and default py…

How does the in operator determine membership? [duplicate]

This question already has answers here:Set "in" operator: uses equality or identity?(5 answers)Closed 7 years ago.How does the in operator work for Python? In the example below I have two n…

Python Automatically ignore unicode string

Ive been searching to automatically import some files but since Im on Windows i got the unicode error (because of the "C:\Users\..."). Ive been looking to correct this error and found some h…