如何在JSON中搜索关键字

2024-09-28 05:27:37 发布

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

我使用的是python json,我想让我的python代码在json文件中搜索specefic关键字

基本上,它应该搜索“profilename”,然后向下一行打印出配置文件的电子邮件

[
  {
    "profilename": "Test123"
    "email": "reid.warren@undefined.name",
    "phone": "+1 (983) 443-3504",
    "address": "359 Rapelye Street, Holtville, Marshall Islands, 9692"
  },
  {
    "profilename": "QTest123"
    "email": "amelia.wilkinson@undefined.us",
    "phone": "+1 (831) 563-3240",
    "address": "525 Allen Avenue, Iola, Kentucky, 894"
  }
]

就像代码应该搜索profilename“Test123”并打印出它的电子邮件一样,就像向下一行并打印出电子邮件一样

我尝试了很多方法,但我甚至没有更进一步,因此共享我当前的代码将有助于0:/

谢谢


Tags: 文件代码jsonaddress电子邮件email配置文件phone
3条回答
  1. 将数据反序列化为python对象(本例中为字典列表):
import json

json_str = '''[
  {
    "profilename": "Test123",
    "email": "reid.warren@undefined.name",
    "phone": "+1 (983) 443-3504",
    "address": "359 Rapelye Street, Holtville, Marshall Islands, 9692"
  },
  {
    "profilename": "QTest123",
    "email": "amelia.wilkinson@undefined.us",
    "phone": "+1 (831) 563-3240",
    "address": "525 Allen Avenue, Iola, Kentucky, 894"
  }
]'''

list_of_dicts = json.loads(json_str)
  1. 然后查找并打印您的条目:
profile_entry = next(el for el in list_of_dicts if el['profilename'] == 'Test123')
print(profile_entry['email'])

StopIteration发生在数据中没有profilename == Test123时。有关词典搜索列表here的详细信息

如果我理解正确,您正在尝试通过字段profilename查找配置文件并返回用户的email

profiles = [
    {
        "profilename": "Test123",
        "email": "reid.warren@undefined.name",
        "phone": "+1 (983) 443-3504",
        "address": "359 Rapelye Street, Holtville, Marshall Islands, 9692",
    },
    {
        "profilename": "QTest123",
        "email": "amelia.wilkinson@undefined.us",
        "phone": "+1 (831) 563-3240",
        "address": "525 Allen Avenue, Iola, Kentucky, 894",
    },
]


def get_profile_email(profilename):
    profile = next(
        (item for item in profiles if item["profilename"] == profilename), None
    )
    if profile:
        return profile["email"]
    return None

print(get_profile_email("Test123"))

输出: reid.warren@undefined.name

要从文件加载配置文件,请执行以下操作:

import json

with open("profiles.json", "r") as f:
    profiles = json.loads(f.read())
import json

json = [
  {
    "profilename": "Test123",
    "email": "reid.warren@undefined.name",
    "phone": "+1 (983) 443-3504",
    "address": "359 Rapelye Street, Holtville, Marshall Islands, 9692"
  },
  {
    "profilename": "QTest123",
    "email": "amelia.wilkinson@undefined.us",
    "phone": "+1 (831) 563-3240",
    "address": "525 Allen Avenue, Iola, Kentucky, 894"
  }
]
profile_name =  "Test123"
data = [x for x in json if x['profilename'] in profile_name]
print(data[0]['email'])
>>>reid.warren@undefined.name

相关问题 更多 >

    热门问题