使用Python在JSON中查找值

时间:2016-11-27 09:13:01

标签: python json parsing

我以前成功解析了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

感谢您的支持,伙计们:)

4 个答案:

答案 0 :(得分:13)

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

答案 1 :(得分:7)

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和过滤器

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

输出

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

答案 2 :(得分:0)

数据= [  {    “ id_number”:“ SA4784”,    “ name”:“ Mark”,    “生日”:无  },  {    “ id_number”:“ V410Z8”,    “ name”:“ Vincent”,    “生日”:“ 15/02/1989”  },  {    “ id_number”:“ CZ1094”,    “ name”:“ Paul”,    “生日”:“ 27/09/1994”  } ]

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

输出应为

[{    “ id_number”:“ CZ1094”,    “ name”:“ Paul”,    “生日”:“ 27/09/1994”  }]

答案 3 :(得分:0)

给予

data = [
    {
    "id_number": "SA4784",
    "name": "Mark",
    "birthdate": None               #  the question wrongly contains a null
    },
    {
    "id_number": "V410Z8",
    "name": "Vincent",
    "birthdate": "15/02/1989"
    },
    {
    "id_number": "CZ1094",
    "name": "Paul",
    "birthdate": "27/09/1994"
    }
    ]

要获取“ V410Z8”,您可以使用:

[x for x in data if x["id_number"]=="V410Z8"]

结果:

[{'id_number': 'V410Z8', 'name': 'Vincent', 'birthdate': '15/02/1989'}]