簡體   English   中英

PySpark,通過 JSON 文件導入模式

[英]PySpark, importing schema through JSON file

tbschema.json看起來像這樣:

[{"TICKET":"integer","TRANFERRED":"string","ACCOUNT":"STRING"}]

我使用以下代碼加載它

>>> df2 = sqlContext.jsonFile("tbschema.json")
>>> f2.schema
StructType(List(StructField(ACCOUNT,StringType,true),
    StructField(TICKET,StringType,true),StructField(TRANFERRED,StringType,true)))
>>> df2.printSchema()
root
 |-- ACCOUNT: string (nullable = true)
 |-- TICKET: string (nullable = true)
 |-- TRANFERRED: string (nullable = true)
  1. 當我希望元素的順序與它們在 JSON 中的顯示順序相同時,為什么要對架構元素進行排序。

  2. JSON導出后數據類型integer已經轉換為StringType,如何保留數據類型。

為什么模式元素會被排序,當我想要元素的順序與它們在 json 中出現的順序相同時。

因為不能保證字段的順序。 雖然沒有明確說明,但當您查看 JSON 閱讀器文檔字符串中提供的示例時,它變得顯而易見。 如果您需要特定的排序,您可以手動提供架構:

from pyspark.sql.types import StructType, StructField, StringType

schema = StructType([
    StructField("TICKET", StringType(), True),
    StructField("TRANFERRED", StringType(), True),
    StructField("ACCOUNT", StringType(), True),
])
df2 = sqlContext.read.json("tbschema.json", schema)
df2.printSchema()

root
 |-- TICKET: string (nullable = true)
 |-- TRANFERRED: string (nullable = true)
 |-- ACCOUNT: string (nullable = true)

json導出后數據類型integer已經轉成StringType,如何保留數據類型。

JSON 字段TICKET數據類型是字符串,因此 JSON 讀取器返回字符串。 它是 JSON 閱讀器,而不是某種模式閱讀器。

一般來說,您應該考慮開箱即用的模式支持附帶的一些正確格式,例如ParquetAvroProtocol Buffers 但是如果你真的想玩 JSON 你可以像這樣定義窮人的“模式”解析器:

from collections import OrderedDict 
import json

with open("./tbschema.json") as fr:
    ds = fr.read()

items = (json
  .JSONDecoder(object_pairs_hook=OrderedDict)
  .decode(ds)[0].items())

mapping = {"string": StringType, "integer": IntegerType, ...}

schema = StructType([
    StructField(k, mapping.get(v.lower())(), True) for (k, v) in items])

JSON 的問題在於,對於字段的排序確實沒有任何保證,更不用說處理缺失的字段、不一致的類型等等。 因此,使用上述解決方案實際上取決於您對數據的信任程度。

或者,您可以使用內置模式導入/導出實用程序

暫無
暫無

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

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