当我想要元素与json中出现的顺序相同时,为什么对架构元素进行排序。
因为不能保证字段顺序。尽管没有明确说明,但是当您看一下JSON阅读器doctstring中提供的示例时,它就会变得很明显。如果您需要特定的订购,则可以手动提供架构:
from pyspark.sql.types import StructType, StructField, StringTypeschema = 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后,数据类型整数已转换为StringType,我该如何保留数据类型。
JSON字段的数据类型
TICKET为字符串,因此JSON阅读器返回字符串。它是JSON阅读器,而不是某种形式的阅读器。
通常来说,您应该考虑现成的架构支持随附的某种适当格式,例如Parquet,Avro或Protocol
Buffers。但是,如果您真的想使用JSON,则可以这样定义可怜人的“模式”解析器:
from collections import OrderedDict import jsonwith open("./tbschema.json") as fr: ds = fr.read()items = (json .JSonDeprer(object_pairs_hook=OrderedDict) .depre(ds)[0].items())mapping = {"string": StringType, "integer": IntegerType, ...}schema = StructType([ StructField(k, mapping.get(v.lower())(), True) for (k, v) in items])
JSON的问题在于,对于字段的排序确实没有任何保证,更不用说处理丢失的字段,类型不一致等了。因此,使用上述解决方案实际上取决于您对数据的信任程度。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)