我正在嘗試Engineering Lead從 JSON 文本中提取特定欄位“”及其對應的值,但是,當嘗試直接從 JSON 中提取它時,它會拋出關鍵錯誤,如code1. 由于它不起作用,我決定回圈它來獲取密鑰Engineering Lead,它是值,但它仍然拋出相同的錯誤。任何幫助將不勝感激。
json文本:
{'expand': 'renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations', 'id': '11659640', 'self': '/rest/api/2/issue/11659640', 'key': 'TOOLSTEST-2651', 'fields': {'description': 'h2. Main\r\n * *:*\r\n * *Application ISO:*\xa0Tony Zeinoun\r\n * *Engineering Lead:*\xa0Peter james\r\n * *Application Architect:*\xa0John david\r\n * *Divisional Architect:*\xa0Robert denuvit'}}
代碼1:
engLeadDetails = data_load['fields']['* \*Engineering Lead']
代碼 2:
engLeadDetails = data_load['fields']
for k,v in engLeadDetails.items():
if (k == '* \*Engineering Lead'):
print (v)
錯誤:
Traceback (most recent call last):
File "/Users/peter/abc.py", line 32, in <module>
engLeadDetails = data_load['fields']['* *Engineering Lead']
KeyError: '* *Engineering Lead'
uj5u.com熱心網友回復:
我認為由于缺少引號,python 找不到這樣的鍵。請再次檢查 json 文本。當前似乎* *Engineering Lead是更大字串的一部分,但不是鍵(由于缺少引號)。
uj5u.com熱心網友回復:
KeyError 表示該鍵* \*Engineering Lead在字典中不存在。
描述的分隔符(存盤您的 EngLead 的位置)似乎是 \r\n。
使用它,我們可以拆分描述以獲取每個角色。
job_details = data_load["fields"]["description"]
洗掉任意字串,這給我們留下了
job_details = [
"* *Application ISO:* Tony Zeinoun",
"* *Engineering Lead:* Peter james",
"* *Application Architect:* John david",
"* *Divisional Architect:* Robert denuvit",
]
我假設你想要每個職位的人的名字。
現在我們從每個字串中洗掉任意字符。
job_dict = {}
for s in job_details:
s = s.replace("*","").strip()
job, person = s.split(":")
job_dict[job] = person.strip()
job_dict現在很干凈,可以輕松訪問每個作業。
結果字典:
{
'Application Architect': 'John david',
'Application ISO': 'Tony Zeinoun',
'Divisional Architect': 'Robert denuvit',
'Engineering Lead': 'Peter james'
}
print(job_dict["Engineering Lead"]) # Peter james
uj5u.com熱心網友回復:
您可以通過按順序拆分將 JSON 字串描述轉換為字典,\r\n然后將角色和名稱分解為鍵/值并添加到字典中。
The expression \W* in regexp below will strip off the non-alphanumeric prefix off the roles and names; e.g., "** Application ISO" => "Application ISO", etc.
Try something like this:
data = {}
for s in data_load['fields']['description'].split('\r\n'):
if m := re.search(r'^\W*(.*?):\W*(. )', s):
if label := m.group(1):
data[label] = m.group(2)
print(data)
Output:
{'Application ISO': 'Tony Zeinoun', 'Engineering Lead': 'Peter james', 'Application Architect': 'John david', 'Divisional Architect': 'Robert denuvit'}
Then can grab a particular role/person out:
print(">>", data.get("Engineering Lead"))
Outputs:
>> Peter james
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/456145.html
標籤:Python python-3.x
