簡體   English   中英

將 dataframe 轉換為 JSON(在 pyspark 中),然后選擇所需的字段

[英]Converting a dataframe into JSON (in pyspark) and then selecting desired fields

我是星火的新手。 我有一個 dataframe,其中包含一些分析的結果。 我將 dataframe 轉換為 JSON,這樣我就可以在 Flask 應用程序中顯示它:

results = result.toJSON().collect()

下面是我的 json 文件中的示例條目。 然后我嘗試運行一個 for 循環以獲得特定結果:

{"userId":"1","systemId":"30","title":"interest"}

for i in results:
    print i["userId"]

這根本不起作用,我收到如下錯誤:Python (json): TypeError: expected string or buffer

我使用json.dumpsjson.loads但仍然一無所獲 - 我不斷收到諸如字符串索引必須為整數之類的錯誤以及上述錯誤。

然后我嘗試了這個:

  print i[0]

這給了我 json 中的第一個字符“{”而不是第一行。 我真的不知道該怎么辦,誰能告訴我哪里出錯了?

非常感謝。

如果result.toJSON().collect()是JSON編碼的字符串,那么您將使用json.loads()將其轉換為dict 您遇到的問題是,當您使用for循環迭代dict時,您將獲得dict的鍵。 在你的for循環中,你將關鍵視為dict ,而實際上它只是一個string 試試這個:

# toJSON() turns each row of the DataFrame into a JSON string
# calling first() on the result will fetch the first row.
results = json.loads(result.toJSON().first())

for key in results:
    print results[key]

# To decode the entire DataFrame iterate over the result
# of toJSON()

def print_rows(row):
    data = json.loads(row)
    for key in data:
        print "{key}:{value}".format(key=key, value=data[key])


results = result.toJSON()
results.foreach(print_rows)    

編輯:問題是, collect返回一個list ,而不是一個dict 我已經更新了代碼。 始終閱讀文檔。

collect()返回包含此RDD中所有元素的列表。

注意僅當期望結果數組很小時才應使用此方法,因為所有數據都已加載到驅動程序的內存中。

EDIT2:我不能強調,總是閱讀文檔。

編輯3:這里

import json
>>> df = sqlContext.read.table("n1")
>>> df.show()
+-----+-------+----+---------------+-------+----+
|   c1|     c2|  c3|             c4|     c5|  c6|
+-----+-------+----+---------------+-------+----+
|00001|Content|   1|Content-article|       |2018|
|00002|Content|null|Content-article|Content|2015|
+-----+-------+----+---------------+-------+----+

>>> results = df.toJSON().map(lambda j: json.loads(j)).collect()
>>> for i in results: print i["c1"], i["c6"]
... 
00001 2018
00002 2015

這對我有用:

df_json = df.toJSON()

for row in df_json.collect():
    #json string
    print(row) 

    #json object
    line = json.loads(row) 
    print(line[some_key]) 

請記住,使用.collect()是不可取的,因為它會收集分布式數據幀,並且無法使用數據幀。

要獲取 python 字典的數組:

results = df.toJSON().map(json.loads).collect()

要獲取 JSON 個字符串的數組:

results = df.toJSON().collect()

要獲得 JSON 字符串(即數組的 JSON 字符串):

results = df.toPandas().to_json(orient='records')

並使用它來獲取 Python 字典的數組:

results = json.loads(df.toPandas().to_json(orient='records'))

暫無
暫無

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

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