使用Python在JSON中查找值

2024-04-30 04:29:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我之前已经成功地解析了JSON文件中的数据,但现在我要实现的函数遇到了问题。我有一个JSON格式的姓名、身份证号码和出生日期列表。我想在Python中得到的是让用户输入一个名字并检索他的身份证号码和出生日期(如果有的话)。

这是我的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

谢谢你们的支持,伙计们:)


Tags: 文件数据nameidjsonnumberdata名字
3条回答

在Python中使用lamda

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"
 }
]

使用Lambda和filter

print(list(filter(lambda x:x["id_number"]=="CZ1094",data)))

输出

[{'id_number': 'CZ1094', 'name': 'Paul', 'birthdate': '27/09/1994'}]

数据=[ { “身份证号码”:“SA4784”, “name”:“标记”, “生日”:无 }, { “id_number”:“V410Z8”, “name”:“文森特”, “出生日期”:“1989年2月15日” }, { “身份证号码”:“CZ1094”, “name”:“保罗”, “出生日期”:“1994年9月27日” } ]

列表(映射(如果x[“id_number”]=“cz1094”,则为lamba x:x,数据]

输出应该是

[{ “身份证号码”:“CZ1094”, “name”:“保罗”, “出生日期”:“1994年9月27日” }]

您必须遍历字典列表并搜索具有给定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"}
        }

然后,您只需尝试直接访问它:

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

相关问题 更多 >