我正在努力将 JSON API 响应转换为
pandas Dataframe
对象。我已阅读类似问题/文档的答案,但没有任何帮助。
以下是我尝试创建的函数的一部分:
以下是调用API时的响应:
{
'applicantId': '1006086625',
'refApplicantId': None,
'CompanyTaxStatus': {
'RFC': 'XXXX000000X00',
'PayingTax': 'POSITIVO',
'ReportDataUpdateDate': '2023-08-02T00: 00: 00'
},
'CompanyObligationsList': None,
'Success': True,
'message': None
}{
"applicantId": "1006086625",
"refApplicantId": null,
"CompanyTaxStatus": {
"RFC": "XXXX000000X00",
"PayingTax": "POSITIVO",
"ReportDataUpdateDate": "2023-08-02T00:00:00"
},
"CompanyObligationsList": null,
"Success": true,
"message": null
}
我想得到的只是从“CompanyTaxStatus”到
Pandas Dataframe
的信息。
def get_Company_Tax_Status(company_id):
url = f"https://service.com/apiservice.svc/GetCompanyTaxStatus?taxId={company_id}"
headers = {
'Content-Type': 'application/json',
'apiId': 'XXXXXXXXXXXXX',
'apiKey': 'XXXXXXXXXXXXX',
'Accept-Encoding': 'gzip, deflate'
}
response = requests.request("GET", url, headers=headers)
if response.status_code == 200:
data = response.json()
print("JSON Response: \n", data)
df = pd.read_json(data, orient='records')
print(df.head()) #
else:
print(f"Failed to fetch data: {response.status_code}")
print(response.text)
尝试这样
import requests
import pandas as pd
def get_Company_Tax_Status(company_id):
url = f"https://service.com/apiservice.svc/GetCompanyTaxStatus?taxId={company_id}"
headers = {
'Content-Type': 'application/json',
'apiId': 'XXXXXXXXXXXXX',
'apiKey': 'XXXXXXXXXXXXX',
'Accept-Encoding': 'gzip, deflate'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
print("JSON Response: \n", data)
# Extract "CompanyTaxStatus" and normalize the nested JSON structure
company_tax_status_data = data.get("CompanyTaxStatus", {})
df = pd.json_normalize(company_tax_status_data)
print(df.head()) # Display the DataFrame
else:
print(f"Failed to fetch data: {response.status_code}")
print(response.text)
# Example usage:
get_Company_Tax_Status("your_company_id_here")