【问题标题】:Export specific JSON data to a CSV file in Python将特定的 JSON 数据导出到 Python 中的 CSV 文件
【发布时间】: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)。包括您尝试解决问题的方法以及您的结果与您的预期有何不同。

标签: python json api csv


【解决方案1】:

你可以不使用 pandas 来做到这一点,你只需要 csvjson 模块来读写数据。

假设你的 json 文件只包含单个对象的数据,你可以像使用字典一样通过键调用你的字段,因为你只有 4 个字段:

import csv
import json


header = ['url', 'id', 'name', 'ITSystemCode']

with open('apica_checks_final.json', 'r') as json_file:
    data = json.load(json_file)
    values = [data['url'], data['id'], data['name'], data['tags']['ITSystemCode'][0]]

with open('apica_checks_final.csv', 'w', newline='') as csv_file:
    csv_writer = csv.writer(csv_file)
    csv_writer.writerow(header)
    csv_writer.writerow(values)

如果您的 json 文件包含多个对象,您需要遍历它们,并注意 ITSystemCode 我检索第一个元素 [0] 因为它在您的文件中表示为一个数组,所以对于这个字段您也需要循环如果您有多个,则通过。

CSV文件输出:

url,id,name,ITSystemCode
***,46092,***,***

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    • 2015-06-15
    • 2023-02-26
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    • 1970-01-01
    相关资源
    最近更新 更多