【问题标题】:udf to parse string json in pyspark dataframeudf 解析 pyspark 数据帧中的字符串 json
【发布时间】:2023-03-30 15:50:01
【问题描述】:

我有一个包含字符串 json 的 pyspark 数据框。如下所示:

+---------------------------------------------------------------------------+
|col                                                                        | 
+---------------------------------------------------------------------------+
|{"fields":{"list1":[{"list2":[{"list3":[{"type":false}]}]}]}}            | 
+----------------------------------------------------------------------------+--

我写了udfs尝试解析json然后计算匹配phone的值并返回df中的新列

def item_count(json,type):
    count=0
    for i in json.get("fields",{}).get("list1",[]):
        for j in i.get("list2",[]):
            for k in j.get("list3",[]):
                count+=k.get("type",None)==type
    return count

def item_phone_count(json):
    return item_count(json,False)

df2= df\
.withColumn('item_phone_count', (F.udf(lambda j: item_phone_count(json.loads(j)), t.StringType()))('col'))

但我得到了错误:

AttributeError: 'NoneType' object has no attribute 'get'

知道有什么问题吗?

【问题讨论】:

  • 看起来item_count() 中的变量之一是None,但无法从您发布的信息中确定是哪一个。请发布完整的错误回溯和 minimal reproducible example 并提供足够的信息,以便其他人可以重现您的错误。
  • @craig 你的意思是在 i、j、k 中,其中一个是没有的?
  • 这可能是您所看到的错误的原因。尝试在循环中打印它们,看看其中一个是否为None
  • @Craig 如何打印它,因为我是从 pyspark 数据帧调用 udf?
  • @kihhfeue 尝试从您的数据框中获取一些条目并手动将它们放入函数中,看看会发生什么

标签: python json apache-spark dictionary pyspark


【解决方案1】:

检查无并跳过这些条目:

def item_count(json,type):
    count = 0
    if (json is None) or (json.get("fields",{}) is None):
        return count  
   
    for i in json.get("fields",{}).get("list1",[]):
        if i is None:
            continue
        for j in i.get("list2",[]):
            if j is None:
                continue 
            for k in j.get("list3",[]):
                if k is None:
                    continue 
                count += k.get("type",None) == type
    return count

【讨论】:

  • 错误现在消失了,但不知道为什么当我检查原始 json 并且肯定有符合条件的值时我仍然得到 0 个计数。 json.load 会改变 type 的格式吗?
  • 我对问题进行了一些编辑。类型值为假
猜你喜欢
  • 2017-04-27
  • 2021-06-28
  • 2019-10-17
  • 2021-03-11
  • 2020-12-28
  • 2017-01-23
  • 2019-05-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多