我有一个由函数创建的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"存在。 如果价值" 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
我猜这不是检查价值" person"的正确方法。在JSON密钥中返回,因为它找不到值。我在这里失踪了什么?
我调查了一些这样的线程,并尝试调整我的功能:
使用Python从JSON文件解析值?
在python
中的嵌套json字典中查找值但我的问题是"班级"键。键#34; class"有几个值。 (比如"象牙色")不仅仅是"人"。
答案 0 :(得分:1)
请尝试以下操作:
1假设您的数据存储在python dict中,如果没有尝试转换它。
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
}
使用以下内容将json转换为字符串: 导入json
data_str = json.dumps(data_dict)
现在检查字符串中的单词(data_str):
if 'person' in data_str:
return True
else:
return False
答案 1 :(得分: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
请注意,如果您想计算“人物”出现次数,则不应该在循环内部返回,而是仅在完成后返回。