【发布时间】:2023-01-18 01:28:39
【问题描述】:
因此,我设法将数据从 API 导出到 JSON 文件。接下来是我只需要将特定列导出到 CSV 文件。
这是我的 JSON 数据:
{
"url": "***",
"id": 46092,
"guid": "###",
"name": "***",
"check_type": "***",
"check_type_name": "Real Browser, Chrome",
"check_type_api": "browser",
"enabled": true,
"location": "Finland, Helsinki",
"country_code": "FI",
"sla_percent_current_month": 99.51587285997705,
"timestamp_utc": "2023-01-17T10:25:04.091",
"severity": "I",
"value": 38808,
"unit": "ms",
"target_sla": null,
"check_symbol": "",
"threshold_w": null,
"threshold_w_dynamic": null,
"threshold_e": null,
"threshold_e_dynamic": null,
"threshold_lo_w": null,
"threshold_lo_w_dynamic": null,
"threshold_lo_e": null,
"threshold_lo_e_dynamic": null,
"scheduled_inclusion": null,
"scheduled_exclusion": "mon-sun : 01:00-01:15;",
"interval_seconds": 600,
"last_result_details": {
"message": "10 steps, 10 pages, 255 urls, 175059/44919171 sent/received bytes",
"attempts": 1,
"result_code": 0
},
"tags": {
"24/7 procedure": [
"24/7"
],
"Country": [
"***"
],
"Environment": [
"Prod"
],
"ITSystemCode": [
"***"
]
}
我想导出嵌套到 CSV 文件的 url、id、name 和 ITSystemCode。或者简而言之,我的 CSV 文件中只有特定的列。
这是代码本身:
import requests
import json
import csv
# authorization
auth_key = "***"
url = "***&auth_ticket={auth}".format(auth=auth_key)
response = requests.request("GET", url)
data = response.json()
apica_checks = []
checks_exported = 0
try:
for check in data:
if check["check_type_api"].startswith("browser") or check["check_type_api"].startswith("url"):
apica_checks.append(check)
print(str(check['name']) + " with ID " + str(check['id']) + " added")
checks_exported += 1
with open('apica_checks_final.json', 'w', encoding='utf-8') as file:
json.dump(apica_checks, file, indent=2)
# export json data to a csv file
with open('apica_checks_final.json') as browser_checks_json_file:
browser_jsondata = json.load(browser_checks_json_file)
browser_data_file = open('apica_checks_final.csv', 'w', newline='')
csv_writer = csv.writer(browser_data_file)
count = 0
for data in browser_jsondata:
if count == 0:
header = data.keys()
csv_writer.writerow(header)
count += 1
csv_writer.writerow(data.values())
browser_data_file.close()
except:
print("Something wrong happened, try again!")
print(f"Status code: {response.status_code}")
print(f"{checks_exported} checks exported")
尝试使用 Pandas,但我无法弄清楚。也许你们可以给我一些建议,因为这是我为工作和学习 Python 而做的一些额外的巧妙选择。谢谢!
尝试过使用 Pandas,无法使用以下示例解决这个问题
import pandas as pd
df = pd.DataFrame(data)
df.columns = ["name", "id"]
df.to_csv("data.csv", index=False)
【问题讨论】:
-
你的代码有什么问题?
-
我想导出嵌套到 CSV 文件中的 url、id、名称和 ITSystemCode。目前,当我使用 Pandas 时,它只是导出所有内容或根本不导出。可能是简单的解决方案,但我真的被困在这里。 :/
-
如果您在将 4 个特定字段从 json 转换为 CSV 时遇到问题,那么包括其他字段在内的任何其他内容以及您如何获取数据都与问题无关。请将其分解为 [最小、可重现的示例](stackoverflow.com/help/minimal-reproducible-example)。包括您尝试解决问题的方法以及您的结果与您的预期有何不同。