-2

我正在使用 python json,我想让我的 Python 代码在 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"
  }
]

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

我尝试了很多事情,但我什至没有更近一步,所以分享我当前的代码将有助于 0:/

谢谢。

4

3 回答 3

2

如果我理解正确,您正在尝试按字段查找配置文件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())
于 2021-05-04T09:35:46.677 回答
2
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

于 2021-05-04T09:55:19.390 回答
0
  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在你的数据中发生。更多关于字典列表的搜索在这里

于 2021-05-04T09:42:48.523 回答