python 从JSON输出中切片和提取特定值

yeotifhr  于 2023-03-21  发布在  Python
关注(0)|答案(2)|浏览(171)

我正在查询一个REST API,我需要从下面的适配器输出中选择2个字段,查询将包括多个事件编号。
我基本上需要从下面的输出事件编号和描述列表。
获取数据的代码:

headers = {'content-type': 'application/json', 'Authentication-Token': authToken}
response = requests.post('http://dev.startschools.local:2031/baocdp/rest/process/:ITSM_Interface:IncidentManagement:QueryIncident/execute', headers=headers, data=json.dumps(get_query_inc_json()))
 
print(response.text)

response.text printed输出:

[{"name":"Adapter_Output","value":"<query-action-result><entries><metadata><entry-count>2</entry-count></metadata><entry id=\"INC000003197686|INC000003197686\"><field name=\"Incident Number\">INC000021</field><field name=\"Description\">Student needs a new card issued</field></entry><entry id=\"INC000003198967|INC000003198967\"><field name=\"Incident Number\">INC000035</field><field name=\"Description\">Students cannot access the text book portal</field></entry></entries></query-action-result>"}]

我需要获取事件编号和描述的列表,以便循环遍历它们:
事件编号列表1:

["INC000021", "INC000035"]

描述列表2:

["Student needs a new card issued", "Students cannot access the text book portal"]

我尝试使用slice将所有事件编号放入一个列表中,但由于输出不断变化,因此slice无法正常工作。
有谁知道比切片更有效的方法来从这个输出中提取我需要的信息吗?

ukqbszuj

ukqbszuj1#

试试这个。

data = response.text

value = data[0]["value"]
i_nums = [x.split("</field")[0] for x in value.split('<field name=\"Incident Number\">')[1:]]
desc = [x.split("</field")[0] for x in value.split('<field name=\"Description\">')[1:]]

print(i_nums)
print(desc)
zdwk9cvp

zdwk9cvp2#

尽管@jjislam的答案为您的示例提供了正确的答案,但我建议您使用适当的xml解析器来浏览结果,因为这是首先使用结构化数据的实际意图!
这是一个关于如何使用内置xml.etree包的代码片段。一旦你了解了这里发生的事情,你就可以很容易地将它转换成一个带有解析的单行程序。

import xml.etree.ElementTree

responseText = [{"name":"Adapter_Output","value":"<query-action-result><entries><metadata><entry-count>2</entry-count></metadata><entry id=\"INC000003197686|INC000003197686\"><field name=\"Incident Number\">INC000021</field><field name=\"Description\">Student needs a new card issued</field></entry><entry id=\"INC000003198967|INC000003198967\"><field name=\"Incident Number\">INC000035</field><field name=\"Description\">Students cannot access the text book portal</field></entry></entries></query-action-result>"}]

# the root will be the topmost element, in this case the one with tag "query-action-result"
root = xml.etree.ElementTree.fromstring(responseText[0]["value"])
incidents, descriptions = [], []

# iterate recursively over all elements with tag "entry" that are children of the root element
for entry in root.iter('entry'): 
    # within each entry, find the first element with tag "field" and attribute "name=Incident Number", and capture its content
    incident = entry.find("field[@name='Incident Number']").text
    # same, but with attribute "name=Description"
    description = entry.find("field[@name='Description']").text
    print(incident, description)
    incidents.append(incident)
    descriptions.append(description)

print(incidents)
print(descriptions)

相关问题