簡體   English   中英

將 JSON 數組加載到 BigQuery 中

[英]Loading JSON Array Into BigQuery

我正在嘗試將 json 數組加載到 bigquery 表中。 數據結構如下:

[{"image":"testimage1","component":"component1"},{"image":"testimage2","component":"component2"}]

每條 json 記錄對應 BigQuery 中的 1 行。 BigQuery 中的列是:圖像和組件。 當我嘗試攝取數據時,它因解析錯誤而失敗。 如果我嘗試將結構更改為此,它會起作用

 {"image":"testimage1","component":"component1"}{"image":"testimage2","component":"component2"}

我正在嘗試以NEWLINE_DELIMITED_JSON的形式攝取 有什么方法可以讓第一個 json 結構被攝取到 Bigquery 中嗎?

不,BigQuery 只能提取有效的 JSON,而有效的 JSON 不以數組開頭。

你必須稍微改變它:

  • 將其轉換為有效的 JSON(在開頭添加一個{"object":並以}結束該行)。 在臨時表中提取 JSON 並執行查詢以掃描新表並將正確的值插入目標表中
  • 或者刪除數組定義[]並將},{替換為}\n{以獲得 JSON 行。

或者,您可以將 JSON 作為 CSV 文件提取(其中只有 1 列 JSON 原始文本),然后使用 BigQuery 字符串 function 轉換數據並將它們插入目標數據庫。

您可以按照這種循環遍歷列表並將其寫入 json 文件的方法; 然后將 json 文件加載到 BigQuery 中。

from google.cloud import bigquery
from google.oauth2 import service_account
import json

client = bigquery.Client(project="project-id")

dataset_id = "dataset-id"
table_id = "bqjson"


list_dict =[{"image":"testimage1","component":"component1"},{"image":"testimage2","component":"component2"}]


with open ("sample-json-data.json", "w") as jsonwrite:
   for item in list_dict:
       jsonwrite.write(json.dumps(item) + '\n')     #newline delimited json file


dataset_ref = client.dataset(dataset_id)
table_ref = dataset_ref.table(table_id)


job_config = bigquery.LoadJobConfig()
job_config.source_format = bigquery.SourceFormat.NEWLINE_DELIMITED_JSON
job_config.autodetect = True

with open("sample-json-data.json", "rb") as source_file:
   job = client.load_table_from_file(
       source_file,
       table_ref,
       location="us",  # Must match the destination dataset location.
       job_config=job_config,
   )  # API request

job.result()  # Waits for table load to complete.

print("Loaded {} rows into {}:{}.".format(job.output_rows, dataset_id, table_id))

Output:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM