To convert JSON to CSV in Scala, you can use a library such as play-json for JSON parsing and opencsv for CSV writing. Here's an example of how you can achieve this:

  1. Add the required dependencies to your project's build configuration. If you're using SBT, add the following lines to your build.sbt file:
scala
libraryDependencies += "com.typesafe.play" %% "play-json" % "2.9.2" libraryDependencies += "com.opencsv" % "opencsv" % "5.5.2"
  1. Import the necessary classes and packages in your Scala code:
scala
import play.api.libs.json._ import au.com.bytecode.opencsv.CSVWriter import java.io.FileWriter
  1. Define a function to convert the JSON to CSV:
scala
def jsonToCsv(json: JsValue, filePath: String): Unit = { val writer = new CSVWriter(new FileWriter(filePath)) // Extract column headers from the JSON keys val headers = (json \\ "key").map(_.as[String]).distinct.toArray writer.writeNext(headers) // Extract values for each row and write them to the CSV (json \\ "data").foreach { data => val row = headers.map(key => (data \ key).as[String]) writer.writeNext(row) } writer.close() }
  1. Use the jsonToCsv function to convert your JSON to CSV. Provide the JSON data as a JsValue and the desired output file path:
scala
val jsonData = Json.parse("""{ "key": ["Name", "Age", "City"], "data": [ {"Name": "John", "Age": "30", "City": "New York"}, {"Name": "Alice", "Age": "25", "City": "London"} ] }""") jsonToCsv(jsonData, "output.csv")

This example assumes that the JSON data has a "key" field containing an array of column names, and a "data" field containing an array of objects representing the rows.

The jsonToCsv function reads the JSON, extracts the column headers, writes them as the first row in the CSV file, and then iterates over the "data" field to extract the values for each row and write them to the CSV.

After running the code, you should find a file named "output.csv" in the specified location, containing the CSV representation of your JSON data.

Feel free to adjust the code based on your JSON structure and specific requirements for CSV formatting.

Have questions or queries?
Get in Touch