如何在 JSON 中搜索关键字

How to search for Keywords in JSON

我正在使用 python json,我想让我的 Python 代码在 JSON 文件中搜索特定关键字。

基本上它应该搜索“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"
  }
]

比如代码应该搜索配置文件名称“Test123”并打印出它的电子邮件,比如向下一行并打印出电子邮件。

我尝试了很多东西,但我什至没有更进一步,所以分享我当前的代码会有所帮助 0 :/

谢谢。

如果我没理解错的话,您是在尝试通过 profilename 和 return 字段来查找用户的 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())
  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'])
当您的数据中没有 profilename == Test123 时,会出现

StopIteration。有关词典搜索列表的更多信息 here

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