Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Apache spark 如何从另一个数据帧创建具有列名和类型的JSON_Apache Spark_Pyspark - Fatal编程技术网

Apache spark 如何从另一个数据帧创建具有列名和类型的JSON

Apache spark 如何从另一个数据帧创建具有列名和类型的JSON,apache-spark,pyspark,Apache Spark,Pyspark,我有一个具有以下模式的数据框架: root |-- Id: integer (nullable = true) |-- Id_FK: integer (nullable = true) |-- Foo: integer (nullable = true) |-- Bar: string (nullable = true) |-- XPTO: string (nullable = true) 从这个数据帧中,我想创建一个JSON文件,其列名和类型如下 { "Id": "integer

我有一个具有以下模式的数据框架:

root
 |-- Id: integer (nullable = true)
 |-- Id_FK: integer (nullable = true)
 |-- Foo: integer (nullable = true)
 |-- Bar: string (nullable = true)
 |-- XPTO: string (nullable = true)
从这个数据帧中,我想创建一个JSON文件,其列名和类型如下

{
 "Id": "integer",
 "Id_FK": "integer",
 "Foo": "integer ",
 "Bar": "string",
 "XPTO": "string",
}

我正试图使用pyspark实现这一点,但我找不到任何方法来实现这一点。有人能帮我吗?

这里有一个解决方案,首先在模式的列之间迭代填充字典。然后我们使用
json.dumps
将字典转换为字符串:

从pyspark.sql.types导入StructType、StructField、StringType、IntegerType
导入json
#示例模式
schema=StructType(
[
StructField(“Id_FK”,IntegerType()),
StructField(“Foo”,IntegerType()),
StructField(“Bar”,StringType()),
StructField(“XPTO”,StringType())
])
#创建一个字典,其中每个项都是一对col\u name:col\u type
dict={}
对于模式中的c:
dict[c.name]=str(c.dataType)
#转换为json字符串
data=json.dumps(dict)
#保存到文件
text_file=open(“output.txt”、“w”)
text_file.write(数据)
text_file.close()