项目中:Json文件的读取
- 举例:Json文件内容如下(Flickr8k)
{'images':
[{'sentids': [39300, 39301, 39302, 39303, 39304],
'imgid': 7860,
'sentences': [{'tokens': ['a', 'girl', 'in', 'blue', 'is', 'jumping', 'on', 'the', 'shore', 'as', 'small', 'waves', 'approach', 'her'],
'raw': 'A girl in blue is jumping on the shore as small waves approach her .', 'imgid': 7860, 'sentid': 39300},
{'tokens': ['a', 'girl', 'leaps', 'into', 'the', 'air', 'while', 'standing', 'by', 'the', 'ocean'],
'raw': 'A girl leaps into the air while standing by the ocean .', 'imgid': 7860, 'sentid': 39301},
{'tokens': ['a', 'young', 'long', 'haired', 'girl', 'on', 'the', 'beach', 'is', 'jumping', 'in', 'the', 'air'],
'raw': 'A young , long-haired , girl on the beach , is jumping in the air .', 'imgid': 7860, 'sentid': 39302},
{'tokens': ['the', 'girl', 'is', 'running', 'into', 'the', 'ocean', 'from', 'the', 'shore'],
'raw': 'The girl is running into the ocean from the shore .', 'imgid': 7860, 'sentid': 39303},
{'tokens': ['the', 'girls', 'is', 'jumping', 'into', 'the', 'air', 'on', 'the', 'beach'],
'raw': 'The girls is jumping into the air on the beach .', 'imgid': 7860, 'sentid': 39304}
],
'split': 'test',
'filename': '1174525839_7c1e6cfa86.jpg'}
],
'dataset': 'flickr8k'}
读Json文件
import json
f = json.load("文件位置")# 读Json文件
取Json文件中内容
和列表/字典取元素一样,如下示例:
举例:
import json
result = json.loads('{"images":[{"sentids":[39300, 39301],"sentences":[{"raw":"A girl in blue"}],"spilt":"test","filename":"1.jpg"}],"dataset": "flickr8k"}')
# 查看json文件内容类型:
print("json文件内容类型: \n",type(result)) # <class 'dict'>
# 查看json文件内容:
print("json文件内容: \n",result)
# 查看文件所有的关键词key:
key = result.keys()
print("文件所有的关键词key:\n",key) # dict_keys(['images', 'dataset'])
# 查看文件所有关键词key对应的值value,只显示value,不显示key
value = result.values()
print("文件所有关键词key对应的值value,只显示value,不显示key\n",value)
# 文件为字典,查看key中value的key的value:Eg:查看images中sentids对应的value
sentids_value = result["images"][0]["sentids"]
print("查看images中sentids对应的value\n",sentids_value)
# 文件为字典,查看key中value的key的value:Eg:查看images中sentences中raw对应的value
sentences_value = result["images"][0]["sentences"][0]["raw"]
print("查看images中sentences对应的value\n",sentences_value)
输出结果:
json文件内容类型:
<class 'dict'>
json文件内容:
{'images': [{'sentids': [39300, 39301], 'sentences': [{'raw': 'A girl in blue'}], 'spilt': 'test', 'filename': '1.jpg'}], 'dataset': 'flickr8k'}
文件所有的关键词key:
dict_keys(['images', 'dataset'])
文件所有关键词key对应的值value,只显示value,不显示key
dict_values([[{'sentids': [39300, 39301], 'sentences': [{'raw': 'A girl in blue'}], 'spilt': 'test', 'filename': '1.jpg'}], 'flickr8k'])
查看images中sentids对应的value
[39300, 39301]
查看images中sentences对应的value
A girl in blue