Python 请求从 response.text 中提取数据
Python requests extracting data from response.text
res = callback({"Abn":"123",
"AbnStatus":"Active",
"AbnStatusEffectiveFrom":"2020-12-12",
"Acn":"",
"AddressDate":"2020-02-04",
"AddressPostcode":"1111",
"AddressState":"CTG",
"BusinessName":[],
"EntityName":"SOME NAME",
"EntityTypeCode":"CPP",
"EntityTypeName":"SOME SECTOR",
"Gst":"2000-07-01",
"Message":""})
我收到了回复,我以上面给出的字符串格式进行回复。 (注意:因为文本 'callback' 在前面,所以我无法以 JSON 格式进行回复)
如何迭代字符串以便我可以单独访问所有值:
喜欢:
Abn = 123 or
AbnStatus = 'Active'
我假设您得到的是以下类型的 JSON 数据,如果不是,请尝试删除 "callback("
并按以下方式直接调用 res['Abn']
:
res = {'callback':[{"Abn":"123",
"AbnStatus":"Active",
"AbnStatusEffectiveFrom":"2020-12-12",
"Acn":"",
"AddressDate":"2020-02-04",
"AddressPostcode":"1111",
"AddressState":"CTG",
"BusinessName":[],
"EntityName":"SOME NAME",
"EntityTypeCode":"CPP",
"EntityTypeName":"SOME SECTOR",
"Gst":"2000-07-01",
"Message":""}]}
#calling hierarchy way
print(res['callback'][0]['Abn']) #where 0 indicates the rank of list
print(res['callback'][0]['AbnStatus'])
输出:
123
Active
您尝试解析的响应应该已经是 json 格式,但我不确定为什么不是。如果您仍然需要它,可以将字符串转换为 json 格式,如下所示。
import json
new_res = res.replace("callback(", "")[:-2].strip()
json_res = json.loads(new_res)
print(json_res["Abn"])
print(json_res["AbnStatus"])
res = callback({"Abn":"123",
"AbnStatus":"Active",
"AbnStatusEffectiveFrom":"2020-12-12",
"Acn":"",
"AddressDate":"2020-02-04",
"AddressPostcode":"1111",
"AddressState":"CTG",
"BusinessName":[],
"EntityName":"SOME NAME",
"EntityTypeCode":"CPP",
"EntityTypeName":"SOME SECTOR",
"Gst":"2000-07-01",
"Message":""})
我收到了回复,我以上面给出的字符串格式进行回复。 (注意:因为文本 'callback' 在前面,所以我无法以 JSON 格式进行回复)
如何迭代字符串以便我可以单独访问所有值:
喜欢:
Abn = 123 or
AbnStatus = 'Active'
我假设您得到的是以下类型的 JSON 数据,如果不是,请尝试删除 "callback("
并按以下方式直接调用 res['Abn']
:
res = {'callback':[{"Abn":"123",
"AbnStatus":"Active",
"AbnStatusEffectiveFrom":"2020-12-12",
"Acn":"",
"AddressDate":"2020-02-04",
"AddressPostcode":"1111",
"AddressState":"CTG",
"BusinessName":[],
"EntityName":"SOME NAME",
"EntityTypeCode":"CPP",
"EntityTypeName":"SOME SECTOR",
"Gst":"2000-07-01",
"Message":""}]}
#calling hierarchy way
print(res['callback'][0]['Abn']) #where 0 indicates the rank of list
print(res['callback'][0]['AbnStatus'])
输出:
123
Active
您尝试解析的响应应该已经是 json 格式,但我不确定为什么不是。如果您仍然需要它,可以将字符串转换为 json 格式,如下所示。
import json
new_res = res.replace("callback(", "")[:-2].strip()
json_res = json.loads(new_res)
print(json_res["Abn"])
print(json_res["AbnStatus"])