簡體   English   中英

將 JSON 文件讀入 Spark 時出現 _corrupt_record 錯誤

[英]_corrupt_record error when reading a JSON file into Spark

我有這個 JSON 文件

{
    "a": 1, 
    "b": 2
}

已通過 Python json.dump 方法獲得。 現在,我想使用 pyspark 將這個文件讀入 Spark 中的 DataFrame。 按照文檔,我正在這樣做

sc = SparkContext()

sqlc = SQLContext(sc)

df = sqlc.read.json('my_file.json')

打印 df.show()

打印聲明雖然吐出這個:

+---------------+
|_corrupt_record|
+---------------+
|              {|
|       "a": 1, |
|         "b": 2|
|              }|
+---------------+

任何人都知道發生了什么以及為什么它沒有正確解釋文件?

您需要在輸入文件中每行有一個json對象,請參閱http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrameReader.json

如果您的json文件看起來像這樣,它將為您提供預期的數據幀:

{ "a": 1, "b": 2 }
{ "a": 3, "b": 4 }

....
df.show()
+---+---+
|  a|  b|
+---+---+
|  1|  2|
|  3|  4|
+---+---+

如果要保留JSON文件(不multiLine=True新行字符\\n ),請包含multiLine=True關鍵字參數

sc = SparkContext() 
sqlc = SQLContext(sc)

df = sqlc.read.json('my_file.json', multiLine=True)

print df.show()

在Spark 2.2+中,您可以使用以下命令讀取多行的json文件。

val dataframe = spark.read.option("multiline",true).json( " filePath ")

如果每行有json對象的話,

val dataframe = spark.read.json(filepath)

加入@ Bernhard的絕佳答案

# original file was written with pretty-print inside a list
with open("pretty-printed.json") as jsonfile:
    js = json.load(jsonfile)      

# write a new file with one object per line
with open("flattened.json", 'a') as outfile:
    for d in js:
        json.dump(d, outfile)
        outfile.write('\n')

我想分享我的經驗,我有一個 JSON 列字符串,但使用True表示法,這意味着我有None而不是nullFalsetrue false

解析此列時,spark 會返回一個名為_corrupt_record的列。 所以在解析 JSON 字符串之前我必須做的是用標准的 JSON 表示法替換 Python 表示法:

df.withColumn("json_notation",
    F.regexp_replace(F.regexp_replace(F.regexp_replace("_corrupt_record", "None", "null"), "False", "false") ,"True", "true")

After this transformation I was then able to use for example the function F.from_json() on the json_notation column and here Pyspark was able to correctly parse the JSON object.

發生這種情況的另一個原因可能是文件編碼。 如果您正在閱讀的文件是例如拉丁編碼的,您將遇到此問題。 在讀取文件時嘗試使用.option("encoding", "cp1252")。 這為我解決了這個問題

暫無
暫無

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

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