【问题标题】:Looking for a specific value in JSON file在 JSON 文件中查找特定值
【发布时间】:2017-07-03 23:58:57
【问题描述】:

我有一个由函数创建的 json 文件。

文件如下所示:

    {
  "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
}

我写了一个函数来检查值“person”是否存在。 如果存在值“人”,我将增加

#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

我猜这不是检查 JSON 键中是否返回值“person”的正确方法,因为它没有找到该值。我在这里错过了什么?

我研究了一些类似的线程并尝试调整我的功能:

使用 Python 从 JSON 文件中解析值?

在python的嵌套json字典中查找值

但我的问题是“类”键。关键“类”(如“象牙色”)有几个值,而不仅仅是“人”。

【问题讨论】:

  • @roganjosh:好的

标签: python json iterator key


【解决方案1】:

因为“person”类不一定是“classes”数组的第一个元素中的第一个。你应该遍历那里的所有元素。

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

如果您想检查任何图像/分类器的类条目中是否有“人”,您还需要遍历这些数组:

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

请注意,如果要计算“人”出现的总数,则不应在循环内返回,而应仅在循环完成后返回。

【讨论】:

    【解决方案2】:

    尝试以下:

    1 假设您的数据存储在 python 字典中,如果没有尝试转换它。

       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. 使用以下方法将 json 转换为字符串: 导入json

       data_str = json.dumps(data_dict)
      
    2. 现在检查字符串(data_str)中的单词:

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

    【讨论】:

    • 这种方法会产生很多不好的结果。例如,即使存在字符串 'xxxpersonxxx' 或 'person' 是键等,它也会匹配。
    • 更改格式是我以前的解决方法。但我想继续浏览 json。
    • 数据已经是json,这可能只是一个更大文件的sn-p,因此对于OP可能想要做的测试类型可能会有很多误报.
    • 是的,有点破解,真正的解决方案是一个非常快速的 json c 语言解析器,然后标记每个单词,然后执行查找。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 2022-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多