2016-11-27 81 views
1

我以前成功地从JSON文件解析数据,但现在我正面临着我想要实现的功能的问题。我有一个JSON名称,身份证号码和出生日期的列表。我想在Python中获得的是能够让用户输入一个名称并检索他的识别号码和出生日期(如果存在)。使用Python在JSON中查找值

这是我的JSON示例文件:

[ 
{ 
    "id_number": "SA4784", 
    "name": "Mark", 
    "birthdate": null 
}, 
{ 
    "id_number": "V410Z8", 
    "name": "Vincent", 
    "birthdate": "15/02/1989" 
}, 
{ 
    "id_number": "CZ1094", 
    "name": "Paul", 
    "birthdate": "27/09/1994" 
} 
] 

要清楚,我想输入“V410Z8”,并得到了他的名字和他的出生日期。

我试图在Python中编写一些代码,但我只成功搜索“id_number”而不是“id_number”内部的内容,例如“V410Z8”。

#!/usr/bin/python 
# -*- coding: utf-8 -*- 

import json 

database = "example.json" 
data = json.loads(open(database).read()) 

id_number = data[0]["id_number"] 
print id_number 

感谢您的支持,球员:)

回答

7

你必须遍历字典的列表,并搜索一个给定id_number。一旦找到它,您可以打印其余的数据并中断,假设id_number是唯一的。

data = [ 
{ 
    "id_number": "SA4784", 
    "name": "Mark", 
    "birthdate": None 
}, 
{ 
    "id_number": "V410Z8", 
    "name": "Vincent", 
    "birthdate": "15/02/1989" 
}, 
{ 
    "id_number": "CZ1094", 
    "name": "Paul", 
    "birthdate": "27/09/1994" 
} 
] 

for i in data: 
    if i['id_number'] == 'V410Z8': 
     print(i['birthdate']) 
     print(i['name']) 
     break 

如果你有在数据结构控制,更有效的方法是使用id_number作为重点(再次,假设id_number是唯一的):

data = { "SA4784" : {"name": "Mark", "birthdate": None}, 
      "V410Z8" : { "name": "Vincent", "birthdate": "15/02/1989"}, 
      "CZ1094" : {"name": "Paul", "birthdate": "27/09/1994"} 
     } 

然后,所有你需要do是试图直接访问它:

try: 
    print(data["V410Z8"]["name"]) 
except KeyError: 
    print("ID doesn't exist") 
>> "Vincent" 
+0

非常感谢!一切都很好! – antonioag