[英]How to convert a Spark Dataframe to JSONObject
我的目标是将 DataFrame 转换为 JSONObject 的有效 JSONArray。
我目前正在使用:
val res = df.toJSON.collect()
但我得到一个 Array[String] - JSON 转义字符串数组,即:
["{\"url\":\"http://www.w3schools.com/html/html_form_action.asp?user=123\",\"subnet\":\"32.2.208.1\",\"country\":\"\",\"status_code\":\"200\"}"]
我正在寻找一种将这些字符串转换为实际 JSONObjects 的方法,我找到了一些建议查找和替换字符的解决方案,但我正在寻找更清洁的东西。
我尝试使用 org.json 库将每个字符串转换为 JSONObject,但显然它不是可序列化的对象。
有什么建议吗? 任何可以工作的快速 Scala JSON 库?
或者一般建议如何使用 toJSON 方法。
更新
这有点浪费,但这个选项对我有用:
val res = df.toJSON.map(new JSONObject(_).toString).collect()
由于 JSONObject 不可序列化 - 我可以使用它的 toString 来获取有效的 JSON 格式。
如果您对如何改进它仍有任何建议 - 请告诉我。
您可以使用spray-json将字符串解析为案例类:
import spray.json._
import DefaultJsonProtocol._
case class Data(url: String, subnet: String, country: String, status_code: String)
implicit val dataFormat = jsonFormat4(Data)
val source = Array("{\"url\":\"http://www.w3schools.com/html/html_form_action.asp?user=123\",\"subnet\":\"32.2.208.1\",\"country\":\"\",\"status_code\":\"200\"}")
val data = source(0).parseJson.convertTo[Data]
您可以使用 DataframeWriter 类。
df.write.json(path)
如果输出文件有多个记录/分区,这可能会创建多个部分文件。 然后,您可以编写一个简单的合并实用程序来合并 hdfs/local 文件系统中的部分文件。
如果输出是一个小文件 - 您可以使用 coalesce()
df.coalesce(1).write.json(path)
然后,您可以将其读回 DF。
你可以:
Array[Row]
Map[String,Any]
- 结果将由Array[Map[String,Any]]
implicit val formats = DefaultFormats
val dataFrame = (1 to 10)
.map(i => ("value" + i, i))
.toDF("name", "value")
val maps = dataFrame
.collect
.map(
row => dataFrame
.columns
.foldLeft(Map.empty[String, Any])
(
(acc, item) => acc + (item -> row.getAs[Any](item))
)
)
val json = Serialization.write(maps)
println(json)
I will show how dataframe converted into Json object list in spark.
I/P: Dataframe
O/P Json : [{ "id":"111","Loc":"Pune"},{"id":"2222","Loc":"Mumbai"}]
Sol:->
1] Create Person POJO having id and loc fields.
2] Suppose dataframe named 'myDF'
3] myDF.collect.foreach { record =>
val recMap = record.getValuesMap(myDF.columns).toMap[Any, Any]
val person =new Person
person.setLoc(recMap("LOC"))
jsonList.append(person) //List of Person obj
}
val gson = new Gson //GSON lib
jsonStr = gson.toJson(jsonList.asJava)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.