在數據分析、報告和 ETL 管道中,使用 JSON 和 Pandas DataFrame 是很常見的。雖然 Pandas 提供了 readjson 用於基本解析,但它在處理深度嵌套結構、非常大的文件或 Excel 優先的工作流程時可能會遇到困難。在這裡,Aspose.Cells for Python 提供了幫助。它提供了一個豐富的 JSON 到 Excel 的管道,您可以輕鬆地將其與 Pandas 集成,以獲得乾淨的 DataFrames 進行分析。在這篇博客文章中,您將學習如何在 Python 中將 JSON 轉換為 Pandas 數據框。

將 JSON 轉換為 Pandas DataFrame 的 Python 庫

Aspose.Cells for Python via .NET 是一個強大的電子表格 API,不需要 Microsoft Excel。除了經典的 Excel 自動化,它支持直接的 JSON 匯入和匯出,使其在您希望將 JSON 轉換為 Pandas DataFrame,然後在 Excel 中保存或處理時非常理想。

使用 Aspose.Cells,您可以:

  • 將 JSON 導入工作表,使用 JsonUtility,並提供處理數組和嵌套結構的選項。
  • 將工作表範圍轉換為 Pandas DataFrame 以進行分析和可視化。
  • 在 Excel 文件中創建、加載和處理 JSON,以適應分析管道。
  • 將 DataFrames 匯出回 Excel(XLSX、CSV、ODS、PDF)以進行報告。

簡而言之,這個庫使得將數據從 JSON 移動到 Excel 以進行報告變得容易,而您可以使用 Pandas 進行更深入的分析。 JsonUtility 將 JSON 導入工作表,並且 JsonLayoutOptions 控制數組和嵌套對象的展開方式。

將 JSON 轉換為 DataFrame

Aspose.Cells 直接將 JSON 匯入工作表。然後,您可以讀取標題行和數據行以構建 Pandas DataFrame。

按照以下步驟將 JSON 轉換為 pandas DataFrame:

  1. 創建一個工作簿並獲取第一個工作表。
  2. 配置 JsonLayoutOptions 以將數組視為表格。
  3. 匯入第 0 行,第 0 列的 JSON 字串。
  4. 使用第一行作為欄位標題。
  5. 提取剩餘的行作為數據。
  6. 建立一個 Pandas DataFrame。

以下代碼範例顯示了如何在 Python 中將 JSON 轉換為 pandas DataFrame:

import pandas as pd
import aspose.cells as ac

# 創建一個新的工作簿並獲取第一個工作表(以 0 為基礎的索引)
wb = ac.Workbook()
ws = wb.worksheets.get(0)

# 配置 JSON 在工作表中的佈局方式
options = ac.utility.JsonLayoutOptions()
options.array_as_table = True           # Treat a top-level JSON array as a table (rows/columns)

# 範例 JSON 陣列的簡單物件
json_data = '[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]'

# 將 JSON 匯入工作表,起始於行=0,列=0(儲存格 A1)
ac.utility.JsonUtility.import_data(json_data, ws.cells, 0, 0, options)

# 找到第一行包含數據的行(這將是我們的標題行)
header_idx = ws.cells.min_data_row

# 從該行中提取標題值,以用作 DataFrame 列名稱
columns = [cell.value for cell in ws.cells.rows[header_idx]]

# 擷取所有後續行作為數據(跳過標題行)
data = [
    [cell.value for cell in row]
   for idx, row in enumerate(ws.cells.rows)
    if row and idx != header_idx
]

# 使用收集到的標題和行來構建數據框
df = pd.DataFrame(data, columns=columns)

# 顯示結果
print(df)

Output

    id   name
0  1.0  Alice
1  2.0    Bob

將嵌套的 JSON 轉換為 Pandas DataFrame

如果您的 JSON 包含嵌套對象,Aspose.Cells 使用 JsonUtility 將 JSON 導入工作表,然後您可以將其導出到 DataFrame。JsonLayoutOptions 控制陣列和嵌套對象的擴展方式。

按照以下步驟將嵌套的 JSON 轉換為 pandas DataFrame:

  1. 創建一本工作簿並選擇第一個工作表。
  2. 設置所需的 JsonLayoutOptions 屬性,例如 arrayastable=Trueignorearraytitle=Trueignoreobjecttitle=Truekeptschema=True
  3. 導入位於 0 行,0 列的嵌套 JSON。
  4. 檢測已使用範圍並橫跨整個範圍讀取標題行。
  5. 閱讀同一區間(固定寬度)中的所有後續行。
  6. 建立 DataFrame;可選擇性地轉換數據類型(例如,total 轉換為數字類型)。

以下代碼示例顯示如何在 Python 中將嵌套 JSON 轉換為 pandas DataFrame:

import pandas as pd
import aspose.cells as ac

# 創建工作簿並獲取第一個工作表
wb = ac.Workbook()
ws = wb.worksheets.get(0)

# 嵌套 JSON 的佈局選項
opt = ac.utility.JsonLayoutOptions()
opt.array_as_table = True  # Treat 'orders' array as a table (rows)
opt.ignore_array_title = True  # Do not place a title row for the 'orders' array
opt.ignore_object_title = True  # Do not place extra title rows for nested objects (e.g., 'buyer')
opt.kept_schema = True  # Keep a stable set of columns even if some records miss fields

# 步驟 3:您的嵌套 JSON
nested = '''
{
  "batch": "A1",
  "orders": [
    {"orderId": "1001", "total": "49.90", "buyer": {"city": "NYC", "zip": "10001"}},
    {"orderId": "1002", "total": "79.00", "buyer": {"city": "Boston", "zip": "02108"}}
  ]
}
'''

# 在 A1 匯入 (row=0, col=0) 使用上述選項
ac.utility.JsonUtility.import_data(nested, ws.cells, 0, 0, opt)

# 檢測已使用範圍
first_row = ws.cells.min_data_row
first_col = ws.cells.min_data_column
last_row = ws.cells.max_data_row
last_col = ws.cells.max_data_column

# 閱讀整個使用的列範圍(固定寬度)的標題列
raw_columns = [ws.cells.get(first_row, c).value for c in range(first_col, last_col + 1)]

# 將標題變得安全:將 None/空白替換為 \"Column{n}\" 並轉換為字串
columns = [
    (str(v) if v is not None and str(v).strip() != "" else f"Column{idx + 1}")
   for idx, v in enumerate(raw_columns)
]

# 跨越同一範圍讀取數據行(固定寬度保證對齊)
data = []
for r in range(first_row + 1, last_row + 1):
    row_vals = [ws.cells.get(r, c).value for c in range(first_col, last_col + 1)]
    data.append(row_vals)

# 建構資料框架
df = pd.DataFrame(data, columns=columns)

# 可選:整理列名稱(例如,替換空格)
df.columns = [str(c).strip() for c in df.columns]

# 可選輸入:
# - 保持 ZIP 代碼為字串(前導零很重要)
# - 將總計轉換為數字(將非數字強制為 NaN)
for col in list(df.columns):
    if col.lower().endswith("total"):
        df[col] = pd.to_numeric(df[col], errors="coerce")

# Print
print(df)

Output

     A1  1001  49.90     NYC  10001
0  None  1002  79.00  Boston  02108

注意:如果您啟用 convertnumericordate=True,看起來像數字的字串(例如,總計)可能會轉換為數字,但像 \"02108\" 這樣的郵政編碼可能會失去前導零。如果需要郵政編碼作為字串,請將其保持為 False

將 Excel 轉換為通過 JSON 的 Pandas DataFrame

使用 Aspose.Cells 將任何 Excel 範圍導出為 JSON,然後將該 JSON 加載到 Pandas 作為 DataFrame。這在您需要為服務或管道提供結構化的 JSON 接口時非常有用。

按照以下步驟將 Excel 轉換為通過 JSON 的 pandas DataFrame:

  1. 創建一個新的工作簿,獲取第一個工作表,並添加示例值。
  2. 創建 JsonSaveOptions 以使用預設值。
  3. 將已使用的範圍導出為 JSON 字串,使用 exportrangetojson() 方法。
  4. 將 JSON 字串讀取到 DataFrame 中,使用 pd.readjson(io.StringIO(jsontext)) 方法。
  5. 檢查或處理 DataFrame 以符合需要。

以下代碼範例顯示如何在 Python 中通過 JSON 將 Excel 轉換為 pandas DataFrame:

import io
import pandas as pd
from aspose.cells.utility import JsonUtility  # JSON export utility
from aspose.cells import Workbook, JsonSaveOptions, License

# 建立一個新的工作簿並訪問第一個工作表
workbook = Workbook()
worksheet = workbook.worksheets.get(0)

# 獲取工作表的單元格
cells = worksheet.cells

# 填寫一個小表格(標題 + 行)
cells.get("A1").value = "Name"
cells.get("B1").value = "Age"
cells.get("C1").value = "City"

cells.get("A2").value = "Alice"
cells.get("B2").value = 25
cells.get("C2").value = "New York"

cells.get("A3").value = "Bob"
cells.get("B3").value = 30
cells.get("C3").value = "San Francisco"

cells.get("A4").value = "Charlie"
cells.get("B4").value = 35
cells.get("C4").value = "Los Angeles"

# 設置 JSON 儲存選項(默認設置適用於簡單表格)
json_save_options = JsonSaveOptions()

# 將使用的範圍匯出為 JSON 字串
# maxdisplayrange 會抓取包含數據的整個矩形區域。
json_text = JsonUtility.export_range_to_json(cells.max_display_range, json_save_options)

# 將 JSON 字串讀入 Pandas DataFrame
#    Pandas 可以直接解析 JSON 字串
df = pd.read_json(io.StringIO(json_text))

# 使用 DataFrame
print(df)

Output

      Name  Age           City
0    Alice   25       New York
1      Bob   30  San Francisco
2  Charlie   35    Los Angeles

獲得免費許可證

評估 Aspose.Cells for Python via .NET,無需功能限制,透過申請免費的臨時許可證來實現。訪問 temporary license page 以解鎖全部功能,包括 JSON 匯入(JsonUtility)、佈局控制(JsonLayoutOptions)、架構保護以及數字/日期轉換。

額外的免費資源

您可以使用以下資源深入了解 JSON 匯入、佈局選項以及使用 Aspose.Cells for Python 進行其他 Excel 操作。

結論

將 JSON 轉換為 Pandas DataFrame 在使用 Aspose.Cells for Python 時變得簡單明瞭。您可以可靠地處理嵌套結構,選擇模式穩定性,並在需要時輕鬆導出到 Excel。結合 Pandas 的靈活性以及 Aspose.Cells 中的 JSON/Excel 管道,以簡化數據處理並釋放 Python 中強大的分析能力。

如果您有任何問題,請訪問我們的 免費支持論壇。我們很樂意幫助您。

另見