使用Python在JSON中查找值 [英] Find a value in JSON using Python
问题描述
我以前曾经成功地从JSON文件中解析数据,但是现在我要实现的功能遇到了问题.我在JSON中有一个名称,标识号和生日的列表.我想要在Python中获得的功能是能够让用户输入名称并检索其标识号和生日(如果存在).
I’ve previously succeeded in parsing data from a JSON file, but now I’m facing a problem with the function I want to achieve. I have a list of names, identification numbers and birthdate in a JSON. What I want to get in Python is to be able to let a user input a name and retrieve his identification number and the birthdate (if present).
这是我的JSON示例文件:
This is my JSON example file:
[
{
"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"并获取他的名字和生日.
To be clear, I want to input "V410Z8" and get his name and his birthdate.
我试图用Python编写一些代码,但是我只成功搜索了"id_number",而不是"id_number"内部的内容,例如"V410Z8".
I tried to write some code in Python but I only succeed in searching for "id_number" and not for what is inside "id_number" for example "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
谢谢你们的支持,伙计们:)
Thank you for your support, guys :)
推荐答案
您必须遍历字典列表,并使用给定的id_number
搜索字典.一旦找到它,就可以打印其其余数据并中断,前提是id_number
是唯一的.
You have to iterate over the list of dictionaries and search for the one with the given id_number
. Once you find it you can print the rest of its data and break, assuming id_number
is unique.
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
是唯一的):
If you have control over the data structure, a more efficient way would be to use the id_number
as a key (again, assuming id_number
is unique):
data = { "SA4784" : {"name": "Mark", "birthdate": None},
"V410Z8" : { "name": "Vincent", "birthdate": "15/02/1989"},
"CZ1094" : {"name": "Paul", "birthdate": "27/09/1994"}
}
然后您需要做的就是尝试直接访问它:
Then all you need to do is try to access it directly:
try:
print(data["V410Z8"]["name"])
except KeyError:
print("ID doesn't exist")
>> "Vincent"
这篇关于使用Python在JSON中查找值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!