简体   繁体   English

将 (String, List[(String, String)]) 转换为 JSON object

[英]Convert a (String, List[(String, String)]) to JSON object

I have the data as:我的数据为:

(ID001,List((BookType,[text]),(author,xyz abc),(time,01/12/2019[22:00] CST/PM))),(ID002,List((BookType,[text]),(author,klj fgh),(time,19/02/2019[12:00] CST/AM)))

I need to convert this to a JSON object:我需要将其转换为 JSON object:

{"ID001":{
    "BookType":"[text]",
    "author":"xyz abc",
    "time":"01/12/2019[22:00] CST/PM" 
    },
{"ID002": {
    "BookType":"[text]" , 
    "author":"klj fgh", 
    "time":"19/02/2019[12:00] CST/AM"
    } 
}

I am very new to Scala Spark.我是 Scala Spark 的新手。 Any idea how to convert this.知道如何转换它。

For creating the json use the jackson which has got good utilities.In your case the following done can be using the below code要创建 json,请使用具有良好实用程序的 jackson。在您的情况下,可以使用以下代码完成以下操作

      val mapper = new ObjectMapper`
      val data = ("ID01", List(("BookType", "[text]"),("author", "xyz abc"),"time","01/12/2019[22:00] CST/PM")))
      val id = mapper.createObjectNode()
      val bookDetails = mapper.createObjectNode()
      data._2.foreach(x => {bookDetails.put(x._1, x._2)})
      id.set(data._1, bookDetails)
      println(id.toString)

The output of the above will be as follows上面的output将如下

{"ID01":{"BookType":"[text]","author":"xyz abc","time":"01/12/2019[22:00] CST/PM"}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM