我是 Apache Spark (Java) 的新手,正在尝试创建一个由多个 json 对象组成的文本文件,这些对象表示这两个数据集的组合。 firstToSecondGeneration 很长,所以我省略了 ch3 和 ch99 之间的列。
这是我尝试加入的两个数据集:
Dataset<Row> firstToSecondGeneration
:
名称|ch1|ch2 |ch3 |ch99
鲍勃|乔|詹姆斯| |
苏|乔|詹姆斯| |
约翰| | | |约翰尼
DataSet<Row> secondToThirdGeneration
:
chName,gChname
乔|小乔
乔|约瑟芬
詹姆斯|小詹姆斯
詹姆斯|杰米
约翰尼|小约翰尼
这是我想要返回的:
预期结果:
{
"name": "Bob",
"children": [
{
"childName": "Joe",
"grandChildren":[
{
"grandChildName": "Joe Jr."
},
{
"grandChildName": "Josephine"
}
]
},
{
"childName": "James",
"grandChildren":[
{
"grandChildName": "James Jr."
},
{
"grandChildName": "Jamie"
}
]
}
]
}
{
"name": "Sue",
"children": [
{
"childName": "Joe",
"grandChildren":[
{
"grandChildName": "Joe Jr."
},
{
"grandChildName": "Josephine"
}
]
},
{
"childName": "James",
"grandChildren":[
{
"grandChildName": "James Jr."
},
{
"grandChildName": "Jamie"
}
]
}
]
}
{
"name": "John",
"children": [
{
"childName": "Johnny",
"grandChildren":[
{
"grandChildName": "Johnny Jr."
}
]
}
]
}
我有一个可行的解决方案,我只需收集列表中的所有 chName 并进行一些字符串连接来创建 json 字符串,但我想避免这样做,因为我觉得我没有在当前的解决方案中充分利用 Spark。
要合并两个数据集并创建嵌套 JSON 对象列表,您可以按照以下步骤操作:
这是一个使用 pandas 和 json 的简单示例:
将 pandas 导入为 pd 导入 json
假设 df1 和 df2 是您的数据集 merged_df = pd.merge(df1, df2, on='common_column')
创建具有所需结构的新 JSON 对象 nested_json = json.dumps(merged_df.to_dict('记录'))
转换为 JSON 对象列表 结果 = json.loads(nested_json)
注意:具体实现将取决于您的数据集结构和所需的输出格式。