Python - 通过另一个值访问Json值

时间:2017-03-20 18:53:05

标签: python json

folders_list = {
   "folders": [{
   "id": "866699",
   "name": "Folder1",
    "files_count": 0,
    "size": "0",
    "has_sub": false
    }, {
    "id": "866697",
    "name": "Folder2",
    "files_count": 0,
    "size": "0",
    "has_sub": false
  }]

我需要知道文件夹名称的文件夹ID。我以为我可以将json转换为python字典并执行

folder_id = [f['id'] for f in folders_list if f['name'] == 'Folder2'][0]

但是Python并没有让我把它转换成字典,因为它不能识别" true"和"假"值。

1 个答案:

答案 0 :(得分:1)

json库可以处理数据中的falsetrue

import json

json_str = """
{
   "folders": [{
   "id": "866699",
   "name": "Folder1",
    "files_count": 0,
    "size": "0",
    "has_sub": false
    }, {
    "id": "866697",
    "name": "Folder2",
    "files_count": 0,
    "size": "0",
    "has_sub": false
  }]
}
"""

data = json.loads(json_str)
folders_list = data['folders']
folder_id = [f['id'] for f in folders_list if f['name'] == 'Folder2'][0]
print "folder_id = %s" % folder_id

<强>输出

folder_id = 866697