Spark SqlContext输出JSON格式 [英] Spark SqlContext output JSON format

查看:464
本文介绍了Spark SqlContext输出JSON格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用Spark SqlContext从postgres数据库中检索了数据.

I have retrieved data from postgres Database using Spark SqlContext.

这是示例代码:

        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格式,是否有任何方法可以将此格式转换为JSON或其他特定方式?

I want the output to be in JSON format.Is there any way to convert this format to JSON or other specific way than this?

推荐答案

如果要将DF转换为json,则可以使用以下代码.

If you want to convert the DF to json then you can use following.

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

如果要将其另存为json文件,请使用

If you want to save it as json file then use

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

如果要以列表的形式获取它,请调用take()或collect().有关何时使用这些方法,请参考Spark文档.

If you want to get it as List then call take() or collect(). Please refer Spark doc for when to use these methods.

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

这篇关于Spark SqlContext输出JSON格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆