簡體   English   中英

從 Python 字典中的鍵中獲取值

[英]Fetching the value from the key in Python's dict

我正在從 JSON 中的 'key' 中獲取 'value',但我不知道為什么我無法獲取目標信息。 下面的代碼

import json 
import requests
 
#Person's ID
id=1194452

#Url
info=requests.get(f'https://api.brokercheck.finra.org/search/individual/{id}?hl=true&includePrevious=true&sort=bc_lastname_sort+asc,bc_firstname_sort+asc,bc_middlename_sort+asc,score+desc&wt=json') 

#convert to JSON
x=info.json()

 #Value
 print(x["firstName"])

下面是本例的JSON。 (鏈接中的信息是公開的。因此,我不會刪除 1194452 的詳細信息)。

{'hits': {'total': 1, 'hits': [{'_type': '_doc', '_source': {'content': '{"basicInformation": {"individualId": 1194452, "firstName": "STEPHEN", "middleName": "MICHAEL", "lastName": "SCHULTZ", "otherNames": [], "bcScope": "Active", "iaScope": "NotInScope", "daysInIndustryCalculatedDate": "4/11/1984"}, "currentEmployments": [{"firmId": 5685, "firmName": "PRUCO SECURITIES, LLC.", "iaOnly": "N", "registrationBeginDate": "4/12/1984", "firmBCScope": "ACTIVE", "firmIAScope": "ACTIVE", "iaSECNumber": "52208", "iaSECNumberType": "801", "bdSECNumber": "16402", "branchOfficeLocations": [{"locatedAtFlag": "Y", "supervisedFromFlag": "N", "privateResidenceFlag": "N", "branchOfficeId": "737412", "street1": "445 Broadhollow Road", "street2": "Suite 405", "city": "Melville", "cityAlias": ["DIX HILLS", "HUNTINGTN STA", "HUNTINGTON STATION", "MELVILLE"], "state": "NY", "country": "United States", "zipCode": "11747", "latitude": "40.785118", "longitude": "-73.404965", "geoLocation": "40.785118,-73.404965", "nonRegisteredOfficeFlag": "N", "elaBeginDate": "10/15/2021"}]}], "currentIAEmployments": [], "previousEmployments": [], "previousIAEmployments": [], "disclosureFlag": "N", "iaDisclosureFlag": "N", "disclosures": [], "examsCount": {"stateExamCount": 0, "principalExamCount": 0, "productExamCount": 2}, "stateExamCategory": [], "principalExamCategory": [], "productExamCategory": [{"examCategory": "SIE", "examName": "Securities Industry Essentials Examination", "examTakenDate": "10/1/2018", "examScope": "BC"}, {"examCategory": "Series 6", "examName": "Investment Company Products/Variable Contracts Representative Examination", "examTakenDate": "4/2/1984", "examScope": "BC"}], "registrationCount": {"approvedSRORegistrationCount": 1, "approvedFinraRegistrationCount": 1, "approvedStateRegistrationCount": 1, "approvedIAStateRegistrationCount": 0}, "registeredStates": [{"state": "New York", "regScope": "BC", "status": "APPROVED", "regDate": "4/12/1984"}], "registeredSROs": [{"sro": "FINRA", "status": "APPROVED"}], "brokerDetails": {"hasBCComments": "N", "hasIAComments": "N", "legacyReportStatusDescription": "Not Requested"}}'}}]}}

問題

  1. 由於 type(x) 是 Python 中的 'dict',為什么我不能獲取鍵的值?
  2. JSON 中的“點擊”是什么? 我用谷歌搜索“hits”,發現它是“Hyperlink Induced Topic Search”。

謝謝

在這種情況下, hits數是查詢結果的數量。 它只是這個 API 用來構造其請求響應的鍵。

為了獲得firstName ,您必須沿着嵌套字典(使用鍵訪問元素)和列表(使用索引訪問元素)導航。 由於在您的案例中只有一次命中(給出一個人的 ID 並收到總計 = 1 的響應),您將訪問索引為 0 的唯一命中。

不過需要注意一件事:與content關聯的值是一個 json 字符串。 所以你應該讀作 json。

為了打印所有名字:

import json

x = {'hits': {'total': 1, 'hits': [{'_type': '_doc', '_source': {'content': '{"basicInformation": {"individualId": 1194452, "firstName": "STEPHEN", "middleName": "MICHAEL", "lastName": "SCHULTZ", "otherNames": [], "bcScope": "Active", "iaScope": "NotInScope", "daysInIndustryCalculatedDate": "4/11/1984"}, "currentEmployments": [{"firmId": 5685, "firmName": "PRUCO SECURITIES, LLC.", "iaOnly": "N", "registrationBeginDate": "4/12/1984", "firmBCScope": "ACTIVE", "firmIAScope": "ACTIVE", "iaSECNumber": "52208", "iaSECNumberType": "801", "bdSECNumber": "16402", "branchOfficeLocations": [{"locatedAtFlag": "Y", "supervisedFromFlag": "N", "privateResidenceFlag": "N", "branchOfficeId": "737412", "street1": "445 Broadhollow Road", "street2": "Suite 405", "city": "Melville", "cityAlias": ["DIX HILLS", "HUNTINGTN STA", "HUNTINGTON STATION", "MELVILLE"], "state": "NY", "country": "United States", "zipCode": "11747", "latitude": "40.785118", "longitude": "-73.404965", "geoLocation": "40.785118,-73.404965", "nonRegisteredOfficeFlag": "N", "elaBeginDate": "10/15/2021"}]}], "currentIAEmployments": [], "previousEmployments": [], "previousIAEmployments": [], "disclosureFlag": "N", "iaDisclosureFlag": "N", "disclosures": [], "examsCount": {"stateExamCount": 0, "principalExamCount": 0, "productExamCount": 2}, "stateExamCategory": [], "principalExamCategory": [], "productExamCategory": [{"examCategory": "SIE", "examName": "Securities Industry Essentials Examination", "examTakenDate": "10/1/2018", "examScope": "BC"}, {"examCategory": "Series 6", "examName": "Investment Company Products/Variable Contracts Representative Examination", "examTakenDate": "4/2/1984", "examScope": "BC"}], "registrationCount": {"approvedSRORegistrationCount": 1, "approvedFinraRegistrationCount": 1, "approvedStateRegistrationCount": 1, "approvedIAStateRegistrationCount": 0}, "registeredStates": [{"state": "New York", "regScope": "BC", "status": "APPROVED", "regDate": "4/12/1984"}], "registeredSROs": [{"sro": "FINRA", "status": "APPROVED"}], "brokerDetails": {"hasBCComments": "N", "hasIAComments": "N", "legacyReportStatusDescription": "Not Requested"}}'}}]}}

for hit in x['hits']['hits']:
    person_json = json.loads(hit['_source']['content'])
    print(person_json['basicInformation']['firstName'])

或者獲取第一個(並且僅在本例中)命中的名字:

json.loads(x['hits']['hits'][0]['_source']['content'])['basicInformation']['firstName']

API 響應為 JSON object 但所需數據為 JSON object 數據的string形式。 所以你必須調用 json.loads() 來制作字典和hits意味着列出 object 的數據。

腳本:

import requests
import json

id = 1194452
url = f'https://api.brokercheck.finra.org/search/individual/{id}?hl=true&includePrevious=true&sort=bc_lastname_sort+asc,bc_firstname_sort+asc,bc_middlename_sort+asc,score+desc&wt=json'

response = requests.get(url)
data = response.json()

for hit in data['hits']['hits']:
    content_str = hit['_source']['content']
    content = json.loads(content_str)
    first_name = content['basicInformation']['firstName']
    print(first_name)

Output:

STEPHEN

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM