Looking for a specific value in JSON file

2019-09-16 07:46发布

问题:

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=1
    print (' FUNCTION : jsonanalysis // step There is a person in this image')
    return person
else :
    person = 0
    print (' 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".

回答1:

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 += 1
        print (' 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 += 1
                print (' 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.



回答2:

Try following :

1 Lets assume your data is stored into the python dict, if not try to convert it.

   data_dict =   {
   "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
 }  
  1. Convert the json to string using following: import json

     data_str = json.dumps(data_dict)
    
  2. Now check the word in the string (data_str):

     if 'person' in data_str:
          return True
     else:
          return False