f = open("sample_diction.json","r")
sample_photo_rep = json.loads(f.read())
print sample_photo_rep
f.close()
上面是我的代码正在努力打开文件sample_diction.json并将其内容作为python对象加载到变量sample_photo_rep中。我要做的下一步是编写代码以访问Sample_flickr_obj中的嵌套数据,以创建该照片的所有标签列表(" Sample_diction.json"中的数据)。然后,我想将标签列表保存在称为sample_tags_list的变量中。以下是sample_diction.json中包含的数据。...我只是不确定从哪里开始。任何帮助,将不胜感激。
{
"photo": {
"people": {
"haspeople": 0
},
"dateuploaded": "1467709435",
"owner": {
"username": "Ansel Adams",
"realname": "",
"nsid": "48093195@N03",
"iconserver": "7332",
"location": "",
"path_alias": null,
"iconfarm": 8
},
"publiceditability": {
"canaddmeta": 1,
"cancomment": 1
},
"id": "27820301400",
"title": {
"_content": "Photo1"
},
"media": "photo",
"tags": {
"tag": [
{
"machine_tag": false,
"_content": "nature",
"author": "48093195@N03",
"raw": "Nature",
"authorname": "ac | photo albums",
"id": "48070141-27820301400-5470"
},
{
"machine_tag": false,
"_content": "mist",
"author": "48093195@N03",
"raw": "Mist",
"authorname": "ac | photo albums",
"id": "48070141-27820301400-852"
},
{
"machine_tag": false,
"_content": "mountain",
"author": "48093195@N03",
"raw": "Mountain",
"authorname": "ac | photo albums",
"id": "48070141-27820301400-1695"
}
]
},
"comments": {
"_content": "0"
},
"secret": "c86034becf",
"usage": {
"canblog": 0,
"canshare": 1,
"candownload": 0,
"canprint": 0
},
"description": {
"_content": ""
},
"isfavorite": 0,
"views": "4",
"farm": 8,
"visibility": {
"isfriend": 0,
"isfamily": 0,
"ispublic": 1
},
"rotation": 0,
"dates": {
"taken": "2016-07-05 11:03:52",
"takenunknown": "1",
"takengranularity": 0,
"lastupdate": "1467709679",
"posted": "1467709435"
},
"license": "0",
"notes": {
"note": []
},
"server": "7499",
"safety_level": "0",
"urls": {
"url": [
{
"type": "photopage",
"_content": "https://www.flickr.com/photos/48093195@N03/27820301400/"
}
]
},
"editability": {
"canaddmeta": 0,
"cancomment": 0
}
},
"stat": "ok"
}
嵌套的数据一开始似乎很艰巨,但是如果您逐步逐步进行。
。您从sample_photo_re
开始。这是一个命令,只有一个键。
so:
sample_photo_rep["photo"]
这是另一个命令。有趣的信息似乎在tags
中:
sample_photo_rep["photo"]["tags"]
又一个命令。所以:
sample_photo_rep["photo"]["tags"]["tag"]
这次是列表,因此您可以迭代:
for tag in sample_photo_rep["photo"]["tags"]["tag"]:
print tag
它输出:
{'machine_tag': False, '_content': 'nature', 'author': '48093195@N03', 'raw': 'Nature', 'authorname': 'ac | photo albums', 'id': '48070141-27820301400-5470'}
{'machine_tag': False, '_content': 'mist', 'author': '48093195@N03', 'raw': 'Mist', 'authorname': 'ac | photo albums', 'id': '48070141-27820301400-852'}
{'machine_tag': False, '_content': 'mountain', 'author': '48093195@N03', 'raw': 'Mountain', 'authorname': 'ac | photo albums', 'id': '48070141-27820301400-1695'}
这些都是命令。您可能只是对raw
密钥感兴趣,所以:
for tag in sample_photo_rep["photo"]["tags"]["tag"]:
print tag['raw']
# Nature
# Mist
# Mountain
完成!
如果您有错误(例如KeyError: 'row'
)退后一步并查看数据,则可能使用type(object)
查看它是列表还是dict。
更新:获取[u'nature', u'mist', u'mountain']
:
[unicode(tag) for tag in sample_photo_rep["photo"]["tags"]["tag"]]