how to convert json string to dataframe on spark
Since the function for reading JSON from an RDD got deprecated in Spark 2.2, this would be another option:
val jsonStr = """{ "metadata": { "key": 84896, "value": 54 }}"""
import spark.implicits._ // spark is your SparkSession object
val df = spark.read.json(Seq(jsonStr).toDS)
Here is an example how to convert Json string to Dataframe in Java (Spark 2.2+):
String str1 = "{\"_id\":\"123\",\"ITEM\":\"Item 1\",\"CUSTOMER\":\"Billy\",\"AMOUNT\":285.2}";
String str2 = "{\"_id\":\"124\",\"ITEM\":\"Item 2\",\"CUSTOMER\":\"Sam\",\"AMOUNT\":245.85}";
List<String> jsonList = new ArrayList<>();
jsonList.add(str1);
jsonList.add(str2);
SparkContext sparkContext = new SparkContext(new SparkConf()
.setAppName("myApp").setMaster("local"));
JavaSparkContext javaSparkContext = new JavaSparkContext(sparkContext);
SQLContext sqlContext = new SQLContext(sparkContext);
JavaRDD<String> javaRdd = javaSparkContext.parallelize(jsonList);
Dataset<Row> data = sqlContext.read().json(javaRdd);
data.show();
Here is the result:
+------+--------+------+---+
|AMOUNT|CUSTOMER| ITEM|_id|
+------+--------+------+---+
| 285.2| Billy|Item 1|123|
|245.85| Sam|Item 2|124|
+------+--------+------+---+
For Spark 2.2+:
import spark.implicits._
val jsonStr = """{ "metadata": { "key": 84896, "value": 54 }}"""
val df = spark.read.json(Seq(jsonStr).toDS)
For Spark 2.1.x:
val events = sc.parallelize("""{"action":"create","timestamp":"2016-01-07T00:01:17Z"}""" :: Nil)
val df = sqlContext.read.json(events)
Hint: this is using
sqlContext.read.json(jsonRDD: RDD[Stirng])
overload. There is alsosqlContext.read.json(path: String)
where it reads a Json file directly.
For older versions:
val jsonStr = """{ "metadata": { "key": 84896, "value": 54 }}"""
val rdd = sc.parallelize(Seq(jsonStr))
val df = sqlContext.read.json(rdd)
simple_json = '{"results":[{"a":1,"b":2,"c":"name"},{"a":2,"b":5,"c":"foo"}]}'
rddjson = sc.parallelize([simple_json])
df = sqlContext.read.json(rddjson)
The reference to the answer is https://stackoverflow.com/a/49399359/2187751