2016-09-08 48 views
0

我使用Spark SqlContext从postgres数据库中检索了数据。Spark SqlContext输出JSON格式

下面是示例代码:

 Class.forName(dbDriver); 

     Map<String, String> options = new HashMap<String, String>(); 
     options.put("url", dbUrl); 
     options.put("dbtable", dbTable); 
     options.put("driver", dbDriver); 

     SparkConf conf = new SparkConf().setAppName("JAVA_SPARK") 
       .setMaster("local[2]").set("spark.ui.port‌​", "7077"); 

     JavaSparkContext jsc = new JavaSparkContext(conf); 

     SQLContext sqlContext = new SQLContext(jsc); 

     DataFrame dframe = sqlContext.read().format("jdbc") 
       .options(options).load(); 

     dframe.show(); 

我有以下的输出:

+------+---+ 
| name|age| 
+------+---+ 
|abc | 20| 
|xyz | 4| 
+------+---+ 

我所要的输出是JSON format.Is有什么办法可以这种格式转换为JSON还是比这个更具体的方法?

回答

0

如果您想将DF转换为json,那么您可以使用以下内容。

JavaRDD<String> jsonRDD = dframe.toJSON().toJavaRDD();  
jsonRDD.foreach(data -> { 
     System.out.println(data); 
    }); 

如果你想将其保存为JSON文件,然后使用

dframe.write().json("c:\\temp\\myfile.json"); 

如果你想获得它的名单,然后调用取()或收集()。请参考Spark doc以了解何时使用这些方法。

List<String> mylist = jsonRDD.collect();   
+0

由于它worked.But如何以这种形式获得输出{“名”:“ABC”,“年龄”:“20”}有没有办法实现这一目标。 –

+0

你想用DF做什么?你想把这个DF保存在json文件中吗? – abaghel

+0

我想通过使用DF将检索到的数据从JSON格式传递到前端。 –