在Pyspark中为同一文件解析具有数组类型和对象类型的嵌套json?

时间:2019-05-01 02:17:08

标签: json parsing pyspark

我正在尝试为同一标签(基于子记录的数量)解析具有ArrayType和ObjecType的JSON文件

{
    main:
    {
        "a":1,
        "b":[{ "name"="Joe",         # note that it [{}]**
        "Age"="21"},

        {"name"="John",
        "Age"="21"}    ]
    },
    {
    "a":2,
    "b":{ "name"="Mary",            # note that it {}**
        "Age"="21"}
    }
}

我试图在标签“ b”上强制使用Struct模式,但是它只是拾取第二个元素,而不是第一个。最终目标是将其转换为数据帧

schema = StructType([
    StructField("name", StringType(), True)
    ,StructField("age", StringType(), True)
])

jsonsf=df.select(col('main.a'),explode(col('main.b')).alias("exp_col")
jsonsf=df.select(col('main.a'),from_json(col('exp_col'),schema))

a|name|Age
1|Joe|21
1|John|21
2|MAry|21

0 个答案:

没有答案